context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// File: Sharp.cs, (Translate, Compile, and Run Sharp code) // Purpose: Translates Sharp into C# and, if no errors, calls the C# compiler to produce an exe. // If no error during compilation, the exe file is run. // The .s extension is just a convention, the extension can be anything or nothing. // Usage: Sharp Program.s // Started: Sharp, 04/25/2017, based on RunH.exe code, Started RunH, 09/12/2012, ultimately based on ESL code // Last Mod: 06/25/2017 // Author: Jim Davidson // Notes: Code based on ideas from: // J. Skeet example at: stackoverflow.com/questions/708550/dynamic-compiled-plugins-in-net // SharpScript at http://sharpscript.codeplex.com // Phil Trelford's Array "C# Scripting," 8, 24, 2009 at www.trelford.com/blog/post/C-Scripting.aspx // Dino Esposito, "Scripting with C#," VSj.net zone, 1/28/2005, www.vsj.co.uk.dotnet/display.asp?id=417 // Copyright (c) 2017, Jim Davidson, MIT License at https://opensource.org/licenses/MIT // Command-line compiles with command below: /* CompileSharp.bat */ using System; using System.IO; using System.Text; // For StringBuilder using System.Text.RegularExpressions; // For RegEx using System.CodeDom.Compiler; using Microsoft.CSharp; using System.Collections.Generic; using JSS.Sharp.Core; /// <summary> /// Class for the Sharp program. /// </summary> class Sharp { private static string s_SharpCompileDate = "06/25/2017"; /// <summary> /// Entry point for the Sharp program. /// </summary> /// <param name="args">Command line arguments</param> public static void Main(string[] args) { //SetWindow(); if (S.Contains(args, "/h") || S.Contains(args, "/?")) { SayHelp(); } else if (args.Length < 1) { ErrorMessage(" Error: No source file entered."); S.Say(); SayHelp(); } string sourceFileName = GetSourceFileName(args); // Do not check extension; any extension OK for now, JRD, 09/12/2012 //string extension = Path.GetExtension(sourceFileName) TranslateAndCompile(sourceFileName); } // End of Main() /// <summary> /// Set DOS output window size, position, and color. Then clear screen. /// </summary> private static void SetWindow() { Console.WindowWidth = (int)(0.9 * Console.LargestWindowWidth); Console.WindowHeight = (int)(0.9 * Console.LargestWindowHeight); Console.BackgroundColor = ConsoleColor.DarkBlue; Console.ForegroundColor = ConsoleColor.White; Console.SetWindowPosition(0, 0); S.CLS(); } /// <summary> /// Display Sharp's help screen. /// </summary> private static void SayHelp() { var LINE = new string('-', 90); S.Say(LINE); S.Say(" Sharp compiled on.: {0}", s_SharpCompileDate); S.Say(" JSS.Sharp.Core.DLL: {0}", S.Version); S.Say(" .Net Version......: {0}", Environment.Version.ToString()); S.Say(" Working Directory.: {0}", Environment.CurrentDirectory); String[] arguments = Environment.GetCommandLineArgs(); S.Say(" Command Line......: {0}", String.Join(" ", arguments)); S.Say(" Copyright (c) 2017, Jim Davidson, MIT License, opensource.org/licenses/MIT"); S.Say(LINE + "\n"); S.Say(" Usage..: Sharp [option] MyProgram.s"); S.Say(" Example: Sharp MyProgram.s"); S.Say(" Option.: /h or /? shows this screen.\n"); S.Say(" Sharp..: 1. Translates MyProgram.s to MyProgram.cs."); S.Say(" 2. Compiles MyProgram.cs to MyProgram.exe."); S.Say(" 3. Runs MyProgram.exe.\n"); //S.Say(" The options are /h /?."); //S.Say(" Options are not case sensitive."); //S.Say(" Option: /d- turns off debugging info from being generated. "); //S.Say(" Debug mode, /d+, is on by default."); //S.Say(@"Examples: C:\MyFolder>Sharp MyProgram.s"); //S.Say(@" C:\MyFolder>Sharp /d- MyProgram.s"); Environment.Exit(-1); } /// <summary> /// Get the name of the source file from the command line argument(s). /// </summary> /// <param name="args">Command line arguments</param> /// <returns>Source file name or error msg and help screen.</returns> private static string GetSourceFileName(string[] args) { string sourceFileName = @args[0]; // Not sure if literal string, @, needed here or not, JRD, 4/28/2017 // S.Contains is not case sensitive. sourceFileName = Path.GetFullPath(sourceFileName).Trim(); if (!File.Exists(sourceFileName)) { S.Say(); Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Red; var width = Console.WindowWidth; var msg = String.Format(" Error: Source file could not be found or an invalid option was entered."); msg = msg + new string(' ', width - msg.Length); S.Say(msg); S.Say(" File.: {0} \n", sourceFileName + new string(' ', width - sourceFileName.Length - 9)); Console.ResetColor(); SayHelp(); Environment.Exit(-1); } return sourceFileName; } // End of GetSourceFileName() private static void ErrorMessage(string msg) { S.Say(); Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Red; var width = Console.WindowWidth; msg = msg + new string(' ', width - msg.Length); S.Say(msg); Console.ResetColor(); } /// <summary> /// (1) <b>Translate</b> Sharp code to C# code.<br> /// (2) <b>Compile</b> the C# code to an exe program. If errors, report and exit.</br> /// (3) <b>Run</b> exe program. /// </summary> /// <param name="sourceFileName">Name of Sharp source file</param> /// <example>C# or Sharp /// <code> /// TranslateAndCompile(sourceFileName); /// </code> /// </example> private static void TranslateAndCompile(string sourceFileName) { string baseFileName = Path.GetFileNameWithoutExtension(sourceFileName); string pathNameOnly = Path.GetDirectoryName(sourceFileName); string sharpFileName = Path.GetFileName(sourceFileName); string cSharpFileName = baseFileName + ".cs"; string cSharpPathFileName = Path.Combine(pathNameOnly, baseFileName + ".cs"); string exeFileName = baseFileName + ".exe"; string exePathFileName = Path.Combine(pathNameOnly, baseFileName + ".exe"); var LINE = new string('-', 80); S.Say(LINE); Console.WriteLine(" Sharp.exe version.: {0}", s_SharpCompileDate); Console.WriteLine(" Using .Net version: {0}", Environment.Version.ToString()); Console.WriteLine(" Using path........: {0}", pathNameOnly); Console.WriteLine(" 1. Translating....: {0}", sharpFileName); Console.WriteLine(" to: {0}", cSharpFileName); string[] sourceLines = File.ReadAllLines(sourceFileName); int numLeadingSpaces = 8; string leadingSpaces = new String(' ', numLeadingSpaces); string source = ""; int lineNumber = 1; string trimStartLine; for (int index = 0; index < sourceLines.Length; index++) { // Remove # comment. trimStartLine = sourceLines[index].TrimStart(); if (trimStartLine.StartsWith("#")) { // UPDATE // Minor bug example: # C# was here. --> // C// was here. JRD, 4/30/2017 sourceLines[index] = sourceLines[index].Replace("#", "//"); } // Change "number" keyword to "double?" C# keyword plus nullable indicator. if (trimStartLine.StartsWith("number ")) { sourceLines[index] = sourceLines[index].Replace("number ", "double? "); } // UPDATE // Look for S.Say at beginning of line. This was an experiment in ESL // that should [probably?] be replaced totally with C# 6.0 string interpolation, JRD, 5/15/2017. // If found, translate first item {V} to {0} or {V2} to {0:N2} or {10V3} to {0,10V3}, etc. // The current version only applies to one-line text strings. string format = @"^S.Say"; if (Regex.Match(trimStartLine, format).Success) { sourceLines[index] = TranslateFormatItems(trimStartLine); } // Don't add blank line before 1st line of Sharp code. if (lineNumber == 1) { source = source + leadingSpaces + sourceLines[index]; } else { source = source + "\r\n" + leadingSpaces + sourceLines[index]; } lineNumber++; } // Add the stuff needed to make a legit C# file out of the Sharp code file. string className = "TranslatedFromSharp"; string mainMethod = " static void Main()\r\n"; string blankLine = "\r\n"; StringBuilder sb = new StringBuilder(); sb.Append("// File \"" + cSharpFileName + "\" generated from Sharp code file \"" + sharpFileName + "\".\r\n"); sb.Append("// Compile with C# command below:\r\n"); // Added line 2 sb.Append("/*\r\n"); // Added line 3 sb.Append(@"C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\csc /r:JSS.Sharp.Core.dll " + cSharpFileName + "\r\n"); sb.Append("*/\r\n"); // Added line 5 sb.Append(blankLine); // Added line 6 sb.Append("using System;\r\n"); // Added line 7 sb.Append("using JSS.Sharp.Core;\r\n"); // Added line 8 sb.Append("using System.Threading.Tasks;\r\n"); // Added line 9 sb.Append(blankLine); // Added line 10 sb.Append("class " + className + "\r\n"); // Added line 11 sb.Append("{\r\n"); // Added line 12 sb.Append(" /// transpose operator, A^T.\r\n"); // Added line 13 sb.Append(" public const string T = \"T\";\r\n"); // Added line 14 sb.Append(blankLine); // Added line 15 sb.Append(mainMethod); // Added line 16 sb.Append(" {\r\n"); // Added line 17 int addedPrefixLines = 17; sb.Append(source); sb.Append("\r\n } // End of Main()\r\n\r\n"); sb.Append("} // End of Class " + className + "\r\n\r\n"); sb.Append("// End of File " + cSharpFileName + "\r\n"); string newSource = sb.ToString(); // Setup C# compiler and compile code. Console.WriteLine(" 2. Compiling......: {0}", cSharpFileName); Console.WriteLine(" to: {0}", exeFileName); // Get the provider for Microsoft.CSharp. var provider = CodeDomProvider.CreateProvider("CSharp"); //Console.WriteLine("CSharp compiler.....: {0}", provider.ToString()); var providerOptions = new Dictionary<string, string>(); // Confusing below: v4.0 applies to versions beyond 4.0. // http://stackoverflow.com/questions/13253967/how-to-target-net-4-5-with-csharpcodeprovider providerOptions.Add("CompilerVersion", "v4.0"); // Below explains why 6.0 code does not work with default CSharp // http://stackoverflow.com/questions/31639602/using-c-sharp-6-features-with-codedomprovider-rosyln // Get the provider for Microsoft.CSharp var codeProvider = new CSharpCodeProvider(providerOptions); var parameters = new CompilerParameters { GenerateExecutable = true, IncludeDebugInformation = true, TreatWarningsAsErrors = false, OutputAssembly = exePathFileName }; parameters.ReferencedAssemblies.Add("JSS.Sharp.Core.dll"); //parameters.ReferencedAssemblies.Add("Microsoft.Office.Interop.Word.dll"); removed 2/16/2011, JRD. //parameters.ReferencedAssemblies.Add("Microsoft.Office.Interop.Excel.dll"); // Compile code. var results = codeProvider.CompileAssemblyFromSource(parameters, new[] { newSource }); // If errors, report and exit. string errorText; if (results.Errors.HasErrors) { S.Say(); S.Say("Sharp Errors:"); S.Say("Source file.: {0}", sourceFileName); foreach (CompilerError err in results.Errors) { errorText = err.ErrorText; errorText = ProcessErrorText(errorText); S.Say("Message.....: {0}", errorText); S.Say("Check line..: {0}", err.Line - addedPrefixLines); S.Say("At column...: {0}", err.Column - numLeadingSpaces); } Environment.Exit(-1); } // Write the C# version of the Sharp code file. File.WriteAllText(cSharpPathFileName, newSource); // Run the code. S.Say(" 3. Running........: {0}", exeFileName); S.Say(LINE); results.CompiledAssembly.EntryPoint.Invoke(null, null); } // End of TranslateAndCompileH() /// <summary> /// Translate the Sharp {wwVdd} placeholder format into standard C# format. /// The optional ww digit(s) specify the minimum width of the output field. /// The optional dd digit(s) specify the number of digits to the right of the decimal point. /// </summary> /// <param name="source">The source code to translate.</param> /// <returns>System.String.</returns> /// <example> /// C# or Sharp /// <code> /// S.Say("Test 13V4 placeholder, {13V4}.", 3.14159); /// S.Say("Test 2V4 placeholder, {2V4}.", 3.14159); /// S.Say("Test V placeholder, {V}.", 3.14159); /// S.Say("Test 13V4, 2V4, V, {13V4}, {2V4}, {V}.", 3.14159, 3.14159, 3.14159); /// Output below: /// Test 13V4 placeholder, 3.1416. /// Test 2V4 placeholder, 3.1416. /// Test V placeholder, 3.14. /// Test 13V4, 2V4, V, 3.1416, 3.1416, 3.14. /// </code> /// </example> private static string TranslateFormatItems(string source) { string rtnVal = source; // Case 1: Format item has both minimum width and precision specifiers. // Example: Change "{12V4}" to "{<)><0,>12:N4}" // Note comma before width specifier. string find = @"\{([0-9]+)V([0-9]+)\}"; string replace = @"{<)><0,>$1:N$2}"; string format = Regex.Replace(source, find, replace); // Case 2: Format item has only has precision specifier. // Example: Change "{V4}" to "{<)><0>:N4}" Note no comma before semicolon. find = @"\{V([0-9]+)\}"; replace = @"{<)><0>:N$1}"; format = Regex.Replace(format, find, replace); // Case 3: Format item has only has width specifier. // Example: Change "{10V}" to "{<)><0,>10:N}" // Note comma before width specifier. find = @"\{([0-9]+)V\}"; replace = @"{<)><0,>$1:N}"; format = Regex.Replace(format, find, replace); // Case 4: Format item has no specifiers. // Example: Change "{V}" to "{<)><0>:N}" Note no comma before semicolon. find = @"\{V\}"; replace = @"{<)><0>:N}"; format = Regex.Replace(format, find, replace); // Use the pattern "{<)>" to get the format items split out into "inserts" array below. // I assume this pattern "{<)>" is very rare in normal text, JRD, 1/31/11. // There is probably a more general way to do this, but this should do for now. string[] separators = new[] {"{<)>"}; string[] inserts = format.Split(separators, StringSplitOptions.None); rtnVal = ""; string newItem = ""; int itemNumber = 0; foreach (string item in inserts) { if (item.Contains("<0,>")) { // Cases 1 and 3. newItem = item.Replace("<0,>", "{" + itemNumber + ","); itemNumber++; } else if (item.Contains("<0>")) { // Cases 2 and 4. newItem = item.Replace("<0>", "{" + itemNumber); itemNumber++; } else { // Just use text as in original source. newItem = item; } rtnVal = rtnVal + newItem; } return rtnVal; } // End of TranslateFormatItems() /// <summary> /// Make the error messages we get back from the C# compiler a bit easier to read. /// </summary> /// <param name="errorText"></param> /// <returns>Error message string</returns> private static string ProcessErrorText(string errorText) { string source = errorText; string rtnVal = errorText; // Case 1: Remove "JSS.Sharp.Core." from the error text. string find = @"JSS\.S\.Core\."; string replace = @""; if (Regex.IsMatch(source, find)) { rtnVal = Regex.Replace(source, find, replace); } // Case 2: Change "The type or namespace name..." to "The symbol, '$1', is not defined". find = @"The type or namespace name '([a-z]+)'.*$"; replace = @"The symbol, '$1', is not defined."; if (Regex.IsMatch(source, find)) { rtnVal = Regex.Replace(source, find, replace); } return rtnVal; } // End of ProcessErrorText() } // End of Class: Sharp // End of file: Sharp.cs
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ using System; using System.IO; using System.Collections; using NUnit.Framework; using NPOI.POIFS.Storage; using NPOI.Util; using NPOI.POIFS.FileSystem; using NPOI.POIFS.Common; namespace TestCases.POIFS.Storage { /** * Class to Test BlockListImpl functionality * * @author Marc Johnson */ [TestFixture] public class TestBlockListImpl { /** * Test zap method * * @exception IOException */ [Test] public void TestZap() { BlockListImpl list = new BlockListImpl(); // verify that you can zap anything for (int j = -2; j < 10; j++) { list.Zap(j); } RawDataBlock[] blocks = new RawDataBlock[5]; for (int j = 0; j < 5; j++) { blocks[j] = new RawDataBlock(new MemoryStream(new byte[512])); } ListManagedBlock[] tmp = (ListManagedBlock[])blocks; list.SetBlocks(tmp); for (int j = -2; j < 10; j++) { list.Zap(j); } // verify that all blocks are gone for (int j = 0; j < 5; j++) { try { list.Remove(j); Assert.Fail("removing item " + j + " should not have succeeded"); } catch (IOException ) { } } } /** * Test Remove method * * @exception IOException */ [Test] public void TestRemove() { BlockListImpl list = new BlockListImpl(); RawDataBlock[] blocks = new RawDataBlock[5]; byte[] data = new byte[512 * 5]; for (int j = 0; j < 5; j++) { for (int k = j * 512; k < (j * 512) + 512; k++) { data[k] = (byte)j; } } MemoryStream stream = new MemoryStream(data); for (int j = 0; j < 5; j++) { blocks[j] = new RawDataBlock(stream); } ListManagedBlock[] tmp = (ListManagedBlock[])blocks; list.SetBlocks(tmp); // verify that you can't Remove illegal indices for (int j = -2; j < 10; j++) { if ((j < 0) || (j >= 5)) { try { list.Remove(j); Assert.Fail("removing item " + j + " should have Assert.Failed"); } catch (IOException ) { } } } // verify we can safely and correctly Remove all blocks for (int j = 0; j < 5; j++) { byte[] outPut = list.Remove(j).Data; for (int k = 0; k < 512; k++) { Assert.AreEqual(data[(j * 512) + k], outPut[k], "testing block " + j + ", index " + k); } } // verify that all blocks are gone for (int j = 0; j < 5; j++) { try { list.Remove(j); Assert.Fail("removing item " + j + " should not have succeeded"); } catch (IOException ) { } } } /** * Test SetBAT * * @exception IOException */ [Test] public void TestSetBAT() { BlockListImpl list = new BlockListImpl(); list.BAT = null; list.BAT = new BlockAllocationTableReader(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); try { list.BAT = new BlockAllocationTableReader(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); Assert.Fail("second attempt should have Assert.Failed"); } catch (IOException ) { } } /** * Test fetchBlocks * * @exception IOException */ [Test] public void TestFetchBlocks() { // strategy: // // 1. Set up a single BAT block from which to construct a // BAT. create nonsense blocks in the raw data block ArrayList // corresponding to the indices in the BAT block. // 2. The indices will include very short documents (0 and 1 // block in Length), longer documents, and some screwed up // documents (one with a loop, one that will peek into // another document's data, one that includes an unused // document, one that includes a reserved (BAT) block, one // that includes a reserved (XBAT) block, and one that // points off into space somewhere BlockListImpl list = new BlockListImpl(); ArrayList raw_blocks = new ArrayList(); byte[] data = new byte[512]; int offset = 0; LittleEndian.PutInt(data, offset, -3); // for the BAT block itself offset += LittleEndianConsts.INT_SIZE; // document 1: Is at end of file alReady; start block = -2 // document 2: has only one block; start block = 1 LittleEndian.PutInt(data, offset, -2); offset += LittleEndianConsts.INT_SIZE; // document 3: has a loop in it; start block = 2 LittleEndian.PutInt(data, offset, 2); offset += LittleEndianConsts.INT_SIZE; // document 4: peeks into document 2's data; start block = 3 LittleEndian.PutInt(data, offset, 4); offset += LittleEndianConsts.INT_SIZE; LittleEndian.PutInt(data, offset, 1); offset += LittleEndianConsts.INT_SIZE; // document 5: includes an unused block; start block = 5 LittleEndian.PutInt(data, offset, 6); offset += LittleEndianConsts.INT_SIZE; LittleEndian.PutInt(data, offset, -1); offset += LittleEndianConsts.INT_SIZE; // document 6: includes a BAT block; start block = 7 LittleEndian.PutInt(data, offset, 8); offset += LittleEndianConsts.INT_SIZE; LittleEndian.PutInt(data, offset, 0); offset += LittleEndianConsts.INT_SIZE; // document 7: includes an XBAT block; start block = 9 LittleEndian.PutInt(data, offset, 10); offset += LittleEndianConsts.INT_SIZE; LittleEndian.PutInt(data, offset, -4); offset += LittleEndianConsts.INT_SIZE; // document 8: goes off into space; start block = 11; LittleEndian.PutInt(data, offset, 1000); offset += LittleEndianConsts.INT_SIZE; // document 9: no screw ups; start block = 12; int index = 13; for (; offset < 508; offset += LittleEndianConsts.INT_SIZE) { LittleEndian.PutInt(data, offset, index++); } LittleEndian.PutInt(data, offset, -2); raw_blocks.Add(new RawDataBlock(new MemoryStream(data))); for (int j = raw_blocks.Count; j < 128; j++) { raw_blocks.Add( new RawDataBlock(new MemoryStream(new byte[0]))); } ListManagedBlock[] tmp = (ListManagedBlock[])raw_blocks.ToArray(typeof(RawDataBlock)); list.SetBlocks(tmp); int[] blocks = { 0 }; BlockAllocationTableReader table = new BlockAllocationTableReader(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 1, blocks, 0, -2, list); int[] start_blocks = { -2, 1, 2, 3, 5, 7, 9, 11, 12 }; int[] expected_Length = { 0, 1, -1, -1, -1, -1, -1, -1, 116 }; for (int j = 0; j < start_blocks.Length; j++) { try { ListManagedBlock[] dataBlocks = list.FetchBlocks(start_blocks[j],-1); if (expected_Length[j] == -1) { Assert.Fail("document " + j + " should have Assert.Failed"); } else { Assert.AreEqual(expected_Length[j], dataBlocks.Length); } } catch (IOException) { if (expected_Length[j] == -1) { // no problem, we expected a Assert.Failure here } else { throw; } } } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Storage { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for StorageAccountsOperations. /// </summary> public static partial class StorageAccountsOperationsExtensions { /// <summary> /// Checks that account name is valid and is not in use. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> public static CheckNameAvailabilityResult CheckNameAvailability(this IStorageAccountsOperations operations, StorageAccountCheckNameAvailabilityParameters accountName) { return operations.CheckNameAvailabilityAsync(accountName).GetAwaiter().GetResult(); } /// <summary> /// Checks that account name is valid and is not in use. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CheckNameAvailabilityResult> CheckNameAvailabilityAsync(this IStorageAccountsOperations operations, StorageAccountCheckNameAvailabilityParameters accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> public static StorageAccount Create(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters) { return operations.CreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> CreateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> public static void Delete(this IStorageAccountsOperations operations, string resourceGroupName, string accountName) { operations.DeleteAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Returns the properties for the specified storage account including but not /// limited to name, account type, location, and account status. The ListKeys /// operation should be used to retrieve storage keys. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> public static StorageAccount GetProperties(this IStorageAccountsOperations operations, string resourceGroupName, string accountName) { return operations.GetPropertiesAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Returns the properties for the specified storage account including but not /// limited to name, account type, location, and account status. The ListKeys /// operation should be used to retrieve storage keys. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> GetPropertiesAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetPropertiesWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the account type or tags for a storage account. It can also be used /// to add a custom domain (note that custom domains cannot be added via the /// Create operation). Only one custom domain is supported per storage account. /// In order to replace a custom domain, the old value must be cleared before a /// new value may be set. To clear a custom domain, simply update the custom /// domain with empty string. Then call update again with the new cutsom domain /// name. The update API can only be used to update one of tags, accountType, /// or customDomain per call. To update multiple of these properties, call the /// API multiple times with one change per call. This call does not change the /// storage keys for the account. If you want to change storage account keys, /// use the RegenerateKey operation. The location and name of the storage /// account cannot be changed after creation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to update on the account. Note that only one property can be /// changed at a time using this API. /// </param> public static StorageAccount Update(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Updates the account type or tags for a storage account. It can also be used /// to add a custom domain (note that custom domains cannot be added via the /// Create operation). Only one custom domain is supported per storage account. /// In order to replace a custom domain, the old value must be cleared before a /// new value may be set. To clear a custom domain, simply update the custom /// domain with empty string. Then call update again with the new cutsom domain /// name. The update API can only be used to update one of tags, accountType, /// or customDomain per call. To update multiple of these properties, call the /// API multiple times with one change per call. This call does not change the /// storage keys for the account. If you want to change storage account keys, /// use the RegenerateKey operation. The location and name of the storage /// account cannot be changed after creation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to update on the account. Note that only one property can be /// changed at a time using this API. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> UpdateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the storage account. /// </param> public static StorageAccountKeys ListKeys(this IStorageAccountsOperations operations, string resourceGroupName, string accountName) { return operations.ListKeysAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the storage account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccountKeys> ListKeysAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the storage accounts available under the subscription. Note that /// storage keys are not returned; use the ListKeys operation for this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IEnumerable<StorageAccount> List(this IStorageAccountsOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Lists all the storage accounts available under the subscription. Note that /// storage keys are not returned; use the ListKeys operation for this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<StorageAccount>> ListAsync(this IStorageAccountsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the storage accounts available under the given resource group. /// Note that storage keys are not returned; use the ListKeys operation for /// this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> public static IEnumerable<StorageAccount> ListByResourceGroup(this IStorageAccountsOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Lists all the storage accounts available under the given resource group. /// Note that storage keys are not returned; use the ListKeys operation for /// this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<StorageAccount>> ListByResourceGroupAsync(this IStorageAccountsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='regenerateKey'> /// Specifies name of the key which should be regenerated. key1 or key2 for the /// default keys /// </param> public static StorageAccountKeys RegenerateKey(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey) { return operations.RegenerateKeyAsync(resourceGroupName, accountName, regenerateKey).GetAwaiter().GetResult(); } /// <summary> /// Regenerates the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='regenerateKey'> /// Specifies name of the key which should be regenerated. key1 or key2 for the /// default keys /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccountKeys> RegenerateKeyAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, accountName, regenerateKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> public static StorageAccount BeginCreate(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters) { return operations.BeginCreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> BeginCreateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace WMAP.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmPromotionItem { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmPromotionItem() : base() { KeyPress += frmPromotionItem_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.TextBox withEventsField_txtPrice; public System.Windows.Forms.TextBox txtPrice { get { return withEventsField_txtPrice; } set { if (withEventsField_txtPrice != null) { withEventsField_txtPrice.Enter -= txtPrice_Enter; withEventsField_txtPrice.KeyPress -= txtPrice_KeyPress; withEventsField_txtPrice.Leave -= txtPrice_Leave; } withEventsField_txtPrice = value; if (withEventsField_txtPrice != null) { withEventsField_txtPrice.Enter += txtPrice_Enter; withEventsField_txtPrice.KeyPress += txtPrice_KeyPress; withEventsField_txtPrice.Leave += txtPrice_Leave; } } } public System.Windows.Forms.ComboBox cmbQuantity; private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.Label _LBL_3; public System.Windows.Forms.Label _LBL_2; public System.Windows.Forms.Label _LBL_1; public System.Windows.Forms.Label _LBL_0; public System.Windows.Forms.Label lblPromotion; public System.Windows.Forms.Label lblStockItem; //Public WithEvents LBL As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPromotionItem)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.txtPrice = new System.Windows.Forms.TextBox(); this.cmbQuantity = new System.Windows.Forms.ComboBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdClose = new System.Windows.Forms.Button(); this._LBL_3 = new System.Windows.Forms.Label(); this._LBL_2 = new System.Windows.Forms.Label(); this._LBL_1 = new System.Windows.Forms.Label(); this._LBL_0 = new System.Windows.Forms.Label(); this.lblPromotion = new System.Windows.Forms.Label(); this.lblStockItem = new System.Windows.Forms.Label(); //Me.LBL = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) this.picButtons.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.LBL, System.ComponentModel.ISupportInitialize).BeginInit() this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Edit Promotion Item"; this.ClientSize = new System.Drawing.Size(388, 115); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmPromotionItem"; this.txtPrice.AutoSize = false; this.txtPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtPrice.Size = new System.Drawing.Size(91, 19); this.txtPrice.Location = new System.Drawing.Point(285, 81); this.txtPrice.TabIndex = 5; this.txtPrice.Text = "0.00"; this.txtPrice.AcceptsReturn = true; this.txtPrice.BackColor = System.Drawing.SystemColors.Window; this.txtPrice.CausesValidation = true; this.txtPrice.Enabled = true; this.txtPrice.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPrice.HideSelection = true; this.txtPrice.ReadOnly = false; this.txtPrice.MaxLength = 0; this.txtPrice.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPrice.Multiline = false; this.txtPrice.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPrice.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPrice.TabStop = true; this.txtPrice.Visible = true; this.txtPrice.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtPrice.Name = "txtPrice"; this.cmbQuantity.Size = new System.Drawing.Size(79, 21); this.cmbQuantity.Location = new System.Drawing.Point(90, 81); this.cmbQuantity.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbQuantity.TabIndex = 4; this.cmbQuantity.BackColor = System.Drawing.SystemColors.Window; this.cmbQuantity.CausesValidation = true; this.cmbQuantity.Enabled = true; this.cmbQuantity.ForeColor = System.Drawing.SystemColors.WindowText; this.cmbQuantity.IntegralHeight = true; this.cmbQuantity.Cursor = System.Windows.Forms.Cursors.Default; this.cmbQuantity.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmbQuantity.Sorted = false; this.cmbQuantity.TabStop = true; this.cmbQuantity.Visible = true; this.cmbQuantity.Name = "cmbQuantity"; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.Size = new System.Drawing.Size(388, 39); this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.TabIndex = 0; this.picButtons.TabStop = false; this.picButtons.CausesValidation = true; this.picButtons.Enabled = true; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Visible = true; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Name = "picButtons"; this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdClose.Text = "E&xit"; this.cmdClose.Size = new System.Drawing.Size(73, 29); this.cmdClose.Location = new System.Drawing.Point(303, 3); this.cmdClose.TabIndex = 1; this.cmdClose.TabStop = false; this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.CausesValidation = true; this.cmdClose.Enabled = true; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Name = "cmdClose"; this._LBL_3.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_3.Text = "Price:"; this._LBL_3.Size = new System.Drawing.Size(27, 13); this._LBL_3.Location = new System.Drawing.Point(254, 84); this._LBL_3.TabIndex = 9; this._LBL_3.BackColor = System.Drawing.Color.Transparent; this._LBL_3.Enabled = true; this._LBL_3.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_3.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_3.UseMnemonic = true; this._LBL_3.Visible = true; this._LBL_3.AutoSize = true; this._LBL_3.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_3.Name = "_LBL_3"; this._LBL_2.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_2.Text = "Shrink Size:"; this._LBL_2.Size = new System.Drawing.Size(56, 13); this._LBL_2.Location = new System.Drawing.Point(31, 84); this._LBL_2.TabIndex = 8; this._LBL_2.BackColor = System.Drawing.Color.Transparent; this._LBL_2.Enabled = true; this._LBL_2.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_2.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_2.UseMnemonic = true; this._LBL_2.Visible = true; this._LBL_2.AutoSize = true; this._LBL_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_2.Name = "_LBL_2"; this._LBL_1.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_1.Text = "Stock Item Name:"; this._LBL_1.Size = new System.Drawing.Size(85, 13); this._LBL_1.Location = new System.Drawing.Point(2, 63); this._LBL_1.TabIndex = 7; this._LBL_1.BackColor = System.Drawing.Color.Transparent; this._LBL_1.Enabled = true; this._LBL_1.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_1.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_1.UseMnemonic = true; this._LBL_1.Visible = true; this._LBL_1.AutoSize = true; this._LBL_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_1.Name = "_LBL_1"; this._LBL_0.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_0.Text = "Promotion Name:"; this._LBL_0.Size = new System.Drawing.Size(81, 13); this._LBL_0.Location = new System.Drawing.Point(7, 45); this._LBL_0.TabIndex = 6; this._LBL_0.BackColor = System.Drawing.Color.Transparent; this._LBL_0.Enabled = true; this._LBL_0.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_0.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_0.UseMnemonic = true; this._LBL_0.Visible = true; this._LBL_0.AutoSize = true; this._LBL_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_0.Name = "_LBL_0"; this.lblPromotion.Text = "lblPromotion"; this.lblPromotion.Size = new System.Drawing.Size(286, 17); this.lblPromotion.Location = new System.Drawing.Point(90, 45); this.lblPromotion.TabIndex = 3; this.lblPromotion.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblPromotion.BackColor = System.Drawing.SystemColors.Control; this.lblPromotion.Enabled = true; this.lblPromotion.ForeColor = System.Drawing.SystemColors.ControlText; this.lblPromotion.Cursor = System.Windows.Forms.Cursors.Default; this.lblPromotion.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblPromotion.UseMnemonic = true; this.lblPromotion.Visible = true; this.lblPromotion.AutoSize = false; this.lblPromotion.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblPromotion.Name = "lblPromotion"; this.lblStockItem.Text = "Label1"; this.lblStockItem.Size = new System.Drawing.Size(286, 17); this.lblStockItem.Location = new System.Drawing.Point(90, 63); this.lblStockItem.TabIndex = 2; this.lblStockItem.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblStockItem.BackColor = System.Drawing.SystemColors.Control; this.lblStockItem.Enabled = true; this.lblStockItem.ForeColor = System.Drawing.SystemColors.ControlText; this.lblStockItem.Cursor = System.Windows.Forms.Cursors.Default; this.lblStockItem.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblStockItem.UseMnemonic = true; this.lblStockItem.Visible = true; this.lblStockItem.AutoSize = false; this.lblStockItem.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblStockItem.Name = "lblStockItem"; this.Controls.Add(txtPrice); this.Controls.Add(cmbQuantity); this.Controls.Add(picButtons); this.Controls.Add(_LBL_3); this.Controls.Add(_LBL_2); this.Controls.Add(_LBL_1); this.Controls.Add(_LBL_0); this.Controls.Add(lblPromotion); this.Controls.Add(lblStockItem); this.picButtons.Controls.Add(cmdClose); //Me.LBL.SetIndex(_LBL_3, CType(3, Short)) //Me.LBL.SetIndex(_LBL_2, CType(2, Short)) //Me.LBL.SetIndex(_LBL_1, CType(1, Short)) //Me.LBL.SetIndex(_LBL_0, CType(0, Short)) //CType(Me.LBL, System.ComponentModel.ISupportInitialize).EndInit() this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using Castle.MicroKernel.Registration; using Glass.Mapper.Configuration; using Glass.Mapper.Pipelines.ObjectConstruction; using Glass.Mapper.Umb.CastleWindsor.Pipelines.ObjectConstruction; using NSubstitute; using NUnit.Framework; namespace Glass.Mapper.Umb.CastleWindsor.Tests.Pipelines.ObjectConstruction { [TestFixture] public class WindsorConstructionFixture { [Test] public void Execute_RequestInstanceOfClass_ReturnsInstance() { //Assign var task = new WindsorConstruction(); var context = Context.Create(DependencyResolver.CreateStandardResolver()); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof (StubClass); var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); var service = Substitute.For<AbstractService>(); var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , service); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsTrue(args.Result is StubClass); } [Test] public void Execute_ResultAlreadySet_NoInstanceCreated() { //Assign var task = new WindsorConstruction(); var context = Context.Create(DependencyResolver.CreateStandardResolver()); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubClass); var args = new ObjectConstructionArgs(context, null, typeConfig , null); var result = new StubClass2(); args.Result = result; Assert.IsNotNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsTrue(args.Result is StubClass2); Assert.AreEqual(result, args.Result); } [Test] public void Execute_RequestInstanceOfInterface_ReturnsNullInterfaceNotSupported() { //Assign var task = new WindsorConstruction(); var context = Context.Create(DependencyResolver.CreateStandardResolver()); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubInterface); var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , null); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNull(args.Result); } [Test] public void Execute_RequestInstanceOfClassWithService_ReturnsInstanceWithService() { //Assign var task = new WindsorConstruction(); var resolver = DependencyResolver.CreateStandardResolver() as DependencyResolver; var context = Context.Create(resolver); resolver.Container.Register( Component.For<StubServiceInterface>().ImplementedBy<StubService>().LifestyleTransient() ); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubClassWithService); var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); var service = Substitute.For<AbstractService>(); var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , service); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsTrue(args.Result is StubClassWithService); var stub = args.Result as StubClassWithService; Assert.IsNotNull(stub.Service); Assert.IsTrue(stub.Service is StubService); } [Test] public void Execute_RequestInstanceOfClassWithParameters_NoInstanceReturnedDoesntHandle() { //Assign var task = new WindsorConstruction(); var context = Context.Create(DependencyResolver.CreateStandardResolver()); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubClassWithParameters); string param1 = "test param1"; int param2 = 450; double param3 = 489; string param4 = "param4 test"; var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); typeCreationContext.ConstructorParameters = new object[]{param1, param2, param3, param4}; var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , null); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNull(args.Result); } #region Stubs public class StubClass { } public class StubClass2 { } public interface StubInterface { } public interface StubServiceInterface { } public class StubService: StubServiceInterface { } public class StubClassWithService { public StubServiceInterface Service { get; set; } public StubClassWithService(StubServiceInterface service) { Service = service; } } public class StubClassWithParameters { public string Param1 { get; set; } public int Param2 { get; set; } public double Param3 { get; set; } public string Param4 { get; set; } public StubClassWithParameters( string param1, int param2, double param3, string param4 ) { Param1 = param1; Param2 = param2; Param3 = param3; Param4 = param4; } } #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.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace System { public static partial class PlatformDetection { // // Do not use the " { get; } = <expression> " pattern here. Having all the initialization happen in the type initializer // means that one exception anywhere means all tests using PlatformDetection fail. If you feel a value is worth latching, // do it in a way that failures don't cascade. // public static bool IsUap => IsWinRT || IsNetNative; public static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase); public static bool IsNetNative => RuntimeInformation.FrameworkDescription.StartsWith(".NET Native", StringComparison.OrdinalIgnoreCase); public static bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); public static bool IsWindows7 => IsWindows && GetWindowsVersion() == 6 && GetWindowsMinorVersion() == 1; public static bool IsWindows8x => IsWindows && GetWindowsVersion() == 6 && (GetWindowsMinorVersion() == 2 || GetWindowsMinorVersion() == 3); public static bool IsNotWindows8x => !IsWindows8x; public static bool IsOSX => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); public static bool IsNetBSD => RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD")); public static bool IsOpenSUSE => IsDistroAndVersion("opensuse"); public static bool IsUbuntu => IsDistroAndVersion("ubuntu"); public static bool IsWindowsNanoServer => (IsWindows && !File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "regedit.exe"))); public static bool IsNotWindowsNanoServer => !IsWindowsNanoServer; public static bool IsWindows10Version1607OrGreater => IsWindows && GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 14393; public static bool IsWindows10Version1703OrGreater => IsWindows && GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 15063; public static bool IsArmProcess => RuntimeInformation.ProcessArchitecture == Architecture.Arm; public static bool IsNotArmProcess => !IsArmProcess; // Windows OneCoreUAP SKU doesn't have httpapi.dll public static bool IsNotOneCoreUAP => (!IsWindows || File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "httpapi.dll"))); public static int WindowsVersion => GetWindowsVersion(); public static bool IsNetfx462OrNewer() { if (!IsFullFramework) { return false; } Version net462 = new Version(4, 6, 2); Version runningVersion = GetFrameworkVersion(); return runningVersion != null && runningVersion >= net462; } public static bool IsNetfx470OrNewer() { if (!IsFullFramework) { return false; } Version net470 = new Version(4, 7, 0); Version runningVersion = GetFrameworkVersion(); return runningVersion != null && runningVersion >= net470; } public static bool IsNetfx471OrNewer() { if (!IsFullFramework) { return false; } Version net471 = new Version(4, 7, 1); Version runningVersion = GetFrameworkVersion(); return runningVersion != null && runningVersion >= net471; } public static Version GetFrameworkVersion() { string[] descriptionArray = RuntimeInformation.FrameworkDescription.Split(' '); if (descriptionArray.Length < 3) return null; if (!Version.TryParse(descriptionArray[2], out Version actualVersion)) return null; foreach (Range currentRange in FrameworkRanges) { if (currentRange.IsInRange(actualVersion)) return currentRange.FrameworkVersion; } return null; } private static int s_isWinRT = -1; public static bool IsWinRT { get { if (s_isWinRT != -1) return s_isWinRT == 1; if (!IsWindows || IsWindows7) { s_isWinRT = 0; return false; } byte[] buffer = new byte[0]; uint bufferSize = 0; try { int result = GetCurrentApplicationUserModelId(ref bufferSize, buffer); switch (result) { case 15703: // APPMODEL_ERROR_NO_APPLICATION s_isWinRT = 0; break; case 0: // ERROR_SUCCESS case 122: // ERROR_INSUFFICIENT_BUFFER // Success is actually insufficent buffer as we're really only looking for // not NO_APPLICATION and we're not actually giving a buffer here. The // API will always return NO_APPLICATION if we're not running under a // WinRT process, no matter what size the buffer is. s_isWinRT = 1; break; default: throw new InvalidOperationException($"Failed to get AppId, result was {result}."); } } catch (Exception e) { // We could catch this here, being friendly with older portable surface area should we // desire to use this method elsewhere. if (e.GetType().FullName.Equals("System.EntryPointNotFoundException", StringComparison.Ordinal)) { // API doesn't exist, likely pre Win8 s_isWinRT = 0; } else { throw; } } return s_isWinRT == 1; } } public static bool IsNotWinRT => !IsWinRT; public static bool IsWinRTSupported => IsWinRT || (IsWindows && !IsWindows7); public static bool IsNotWinRTSupported => !IsWinRTSupported; private static Lazy<bool> m_isWindowsSubsystemForLinux = new Lazy<bool>(GetIsWindowsSubsystemForLinux); public static bool IsWindowsSubsystemForLinux => m_isWindowsSubsystemForLinux.Value; public static bool IsNotWindowsSubsystemForLinux => !IsWindowsSubsystemForLinux; public static bool IsNotFedoraOrRedHatOrCentos => !IsDistroAndVersion("fedora") && !IsDistroAndVersion("rhel") && !IsDistroAndVersion("centos"); public static bool IsFedora => IsDistroAndVersion("fedora"); private static bool GetIsWindowsSubsystemForLinux() { // https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364 if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { const string versionFile = "/proc/version"; if (File.Exists(versionFile)) { string s = File.ReadAllText(versionFile); if (s.Contains("Microsoft") || s.Contains("WSL")) { return true; } } } return false; } public static bool IsDebian => IsDistroAndVersion("debian"); public static bool IsDebian8 => IsDistroAndVersion("debian", "8"); public static bool IsUbuntu1404 => IsDistroAndVersion("ubuntu", "14.04"); public static bool IsCentos7 => IsDistroAndVersion("centos", "7"); public static bool IsTizen => IsDistroAndVersion("tizen"); /// <summary> /// Get whether the OS platform matches the given Linux distro and optional version. /// </summary> /// <param name="distroId">The distribution id.</param> /// <param name="versionId">The distro version. If omitted, compares the distro only.</param> /// <returns>Whether the OS platform matches the given Linux distro and optional version.</returns> private static bool IsDistroAndVersion(string distroId, string versionId = null) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { DistroInfo v = ParseOsReleaseFile(); if (v.Id == distroId && (versionId == null || v.VersionId == versionId)) { return true; } } return false; } public static string GetDistroVersionString() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return ""; } DistroInfo v = ParseOsReleaseFile(); return "Distro=" + v.Id + " VersionId=" + v.VersionId + " Pretty=" + v.PrettyName + " Version=" + v.Version; } private static DistroInfo ParseOsReleaseFile() { Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Linux)); DistroInfo ret = new DistroInfo(); ret.Id = ""; ret.VersionId = ""; ret.Version = ""; ret.PrettyName = ""; if (File.Exists("/etc/os-release")) { foreach (string line in File.ReadLines("/etc/os-release")) { if (line.StartsWith("ID=", System.StringComparison.Ordinal)) { ret.Id = RemoveQuotes(line.Substring("ID=".Length)); } else if (line.StartsWith("VERSION_ID=", System.StringComparison.Ordinal)) { ret.VersionId = RemoveQuotes(line.Substring("VERSION_ID=".Length)); } else if (line.StartsWith("VERSION=", System.StringComparison.Ordinal)) { ret.Version = RemoveQuotes(line.Substring("VERSION=".Length)); } else if (line.StartsWith("PRETTY_NAME=", System.StringComparison.Ordinal)) { ret.PrettyName = RemoveQuotes(line.Substring("PRETTY_NAME=".Length)); } } } return ret; } private static string RemoveQuotes(string s) { s = s.Trim(); if (s.Length >= 2 && s[0] == '"' && s[s.Length - 1] == '"') { // Remove quotes. s = s.Substring(1, s.Length - 2); } return s; } private struct DistroInfo { public string Id { get; set; } public string VersionId { get; set; } public string Version { get; set; } public string PrettyName { get; set; } } private static int GetWindowsVersion() { if (IsWindows) { RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX(); osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); Assert.Equal(0, RtlGetVersion(out osvi)); return (int)osvi.dwMajorVersion; } return -1; } private static int GetWindowsMinorVersion() { if (IsWindows) { RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX(); osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); Assert.Equal(0, RtlGetVersion(out osvi)); return (int)osvi.dwMinorVersion; } return -1; } private static int GetWindowsBuildNumber() { if (IsWindows) { RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX(); osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); Assert.Equal(0, RtlGetVersion(out osvi)); return (int)osvi.dwBuildNumber; } return -1; } [DllImport("ntdll.dll")] private static extern int RtlGetVersion(out RTL_OSVERSIONINFOEX lpVersionInformation); [StructLayout(LayoutKind.Sequential)] private struct RTL_OSVERSIONINFOEX { internal uint dwOSVersionInfoSize; internal uint dwMajorVersion; internal uint dwMinorVersion; internal uint dwBuildNumber; internal uint dwPlatformId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] internal string szCSDVersion; } private static int s_isWindowsElevated = -1; public static bool IsWindowsAndElevated { get { if (s_isWindowsElevated != -1) return s_isWindowsElevated == 1; if (!IsWindows || IsWinRT) { s_isWindowsElevated = 0; return false; } IntPtr processToken; Assert.True(OpenProcessToken(GetCurrentProcess(), TOKEN_READ, out processToken)); try { uint tokenInfo; uint returnLength; Assert.True(GetTokenInformation( processToken, TokenElevation, out tokenInfo, sizeof(uint), out returnLength)); s_isWindowsElevated = tokenInfo == 0 ? 0 : 1; } finally { CloseHandle(processToken); } return s_isWindowsElevated == 1; } } private const uint TokenElevation = 20; private const uint STANDARD_RIGHTS_READ = 0x00020000; private const uint TOKEN_QUERY = 0x0008; private const uint TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY; [DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)] public static extern bool GetTokenInformation( IntPtr TokenHandle, uint TokenInformationClass, out uint TokenInformation, uint TokenInformationLength, out uint ReturnLength); [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] public static extern bool CloseHandle( IntPtr handle); [DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)] public static extern bool OpenProcessToken( IntPtr ProcessHandle, uint DesiredAccesss, out IntPtr TokenHandle); // The process handle does NOT need closing [DllImport("kernel32.dll", ExactSpelling = true)] public static extern IntPtr GetCurrentProcess(); [DllImport("kernel32.dll", ExactSpelling = true)] public static extern int GetCurrentApplicationUserModelId( ref uint applicationUserModelIdLength, byte[] applicationUserModelId); public static bool IsNonZeroLowerBoundArraySupported { get { if (s_lazyNonZeroLowerBoundArraySupported == null) { bool nonZeroLowerBoundArraysSupported = false; try { Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 5 }); nonZeroLowerBoundArraysSupported = true; } catch (PlatformNotSupportedException) { } s_lazyNonZeroLowerBoundArraySupported = Tuple.Create<bool>(nonZeroLowerBoundArraysSupported); } return s_lazyNonZeroLowerBoundArraySupported.Item1; } } private static volatile Tuple<bool> s_lazyNonZeroLowerBoundArraySupported; public static bool IsReflectionEmitSupported = !PlatformDetection.IsNetNative; // Tracked in: https://github.com/dotnet/corert/issues/3643 in case we change our mind about this. public static bool IsInvokingStaticConstructorsSupported => !PlatformDetection.IsNetNative; // System.Security.Cryptography.Xml.XmlDsigXsltTransform.GetOutput() relies on XslCompiledTransform which relies // heavily on Reflection.Emit public static bool IsXmlDsigXsltTransformSupported => !PlatformDetection.IsUap; public static Range[] FrameworkRanges => new Range[]{ new Range(new Version(4, 7, 2500, 0), null, new Version(4, 7, 1)), new Range(new Version(4, 6, 2000, 0), new Version(4, 7, 2090, 0), new Version(4, 7, 0)), new Range(new Version(4, 6, 1500, 0), new Version(4, 6, 1999, 0), new Version(4, 6, 2)), new Range(new Version(4, 6, 1000, 0), new Version(4, 6, 1499, 0), new Version(4, 6, 1)), new Range(new Version(4, 6, 55, 0), new Version(4, 6, 999, 0), new Version(4, 6, 0)), new Range(new Version(4, 0, 30319, 0), new Version(4, 0, 52313, 36313), new Version(4, 5, 2)) }; public class Range { public Version Start { get; private set; } public Version Finish { get; private set; } public Version FrameworkVersion { get; private set; } public Range(Version start, Version finish, Version frameworkVersion) { Start = start; Finish = finish; FrameworkVersion = frameworkVersion; } public bool IsInRange(Version version) { return version >= Start && (Finish == null || version <= Finish); } } } }
using System; using System.IO; using System.Runtime.InteropServices; namespace JetBrains.Debugger.Worker.Plugins.Unity { // Modified from https://github.com/Unity-Technologies/MonoDevelop.Debugger.Soft.Unity/blob/unity-staging/iOSOverUsbSupport.cs // // Copyright (c) Unity Technologies // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. public static class Usbmuxd { // Note: This struct is used in .Net for interop. so do not change it, or know what you are doing! // ReSharper disable InconsistentNaming // ReSharper disable FieldCanBeMadeReadOnly.Global [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)] public struct iOSDevice { public int productId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=41)] public string udid; } // ReSharper restore FieldCanBeMadeReadOnly.Global // ReSharper restore InconsistentNaming // Folder structure: // iOSSupport/ - Intel Mac .dylib // x86/ - 32 bit Windows DLL. Obsolete (from iOSOverUsbSupport.cs) // x86_64/ - 64 bit Windows DLL + Linux .so // // Cleaned up in 2021.2+ // iOSSupport/ // arm64/ - 64 bit ARM. Only M1 Mac .dylib // x64/ - 64 bit Intel. Windows .dll, Intel Mac .dylib, Linux .so private const string NativeDylibOsxX64 = @"x64/UnityEditor.iOS.Native.dylib"; private const string NativeDylibOsxArm64 = @"arm64/UnityEditor.iOS.Native.dylib"; private const string NativeDylibOsxFallback = "UnityEditor.iOS.Native.dylib"; private const string NativeDllWinX64 = @"x64\UnityEditor.iOS.Native.dll"; private const string NativeDllWinX64Fallback = @"x86_64\UnityEditor.iOS.Native.dll"; private const string NativeDllWinX86Obsolete = @"x86\UnityEditor.iOS.Native.dll"; private const string NativeSoLinuxX64 = "x64/UnityEditor.iOS.Native.so"; private const string NativeSoLinuxX64Fallback = "x86_64/UnityEditor.iOS.Native.so"; private static readonly IDllLoader ourLoader; private static IntPtr ourNativeLibraryHandle; public delegate bool StartIosProxyDelegate(ushort localPort, ushort devicePort, [MarshalAs(UnmanagedType.LPStr)] string deviceId); public delegate void StopIosProxyDelegate(ushort localPort); public delegate void StartUsbmuxdListenThreadDelegate(); public delegate void StopUsbmuxdListenThreadDelegate(); public delegate uint UsbmuxdGetDeviceCountDelegate(); public delegate bool UsbmuxdGetDeviceDelegate(uint index, out iOSDevice device); public static StartIosProxyDelegate StartIosProxy; public static StopIosProxyDelegate StopIosProxy; public static StartUsbmuxdListenThreadDelegate StartUsbmuxdListenThread; public static StopUsbmuxdListenThreadDelegate StopUsbmuxdListenThread; public static UsbmuxdGetDeviceCountDelegate UsbmuxdGetDeviceCount; public static UsbmuxdGetDeviceDelegate UsbmuxdGetDevice; public static bool Supported => ourLoader != null; public static bool IsDllLoaded => ourNativeLibraryHandle != IntPtr.Zero; // Setup correctly, or throw trying public static void Setup(string iosSupportPath) { string libraryPath; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) libraryPath = GetWindowsNativeLibraryPath(iosSupportPath); else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) libraryPath = GetMacOsNativeLibraryPath(iosSupportPath); else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) libraryPath = GetLinuxNativeLibraryPath(iosSupportPath); else throw new PlatformNotSupportedException("iOS device enumeration not supported on this platform"); LoadNativeLibrary(libraryPath); InitFunctions(); } public static void Shutdown() { if (ourNativeLibraryHandle == IntPtr.Zero) ourLoader.FreeLibrary(ourNativeLibraryHandle); } private static string GetWindowsNativeLibraryPath(string iosSupportPath) { if (RuntimeInformation.ProcessArchitecture == Architecture.X86) return Path.Combine(iosSupportPath, NativeDllWinX86Obsolete); if (RuntimeInformation.ProcessArchitecture != Architecture.X64) { throw new PlatformNotSupportedException("No native library for process architecture " + RuntimeInformation.ProcessArchitecture); } var defaultDllPath = Path.Combine(iosSupportPath, NativeDllWinX64); if (File.Exists(defaultDllPath)) return defaultDllPath; var fallbackDllPath = Path.Combine(iosSupportPath, NativeDllWinX64Fallback); if (File.Exists(fallbackDllPath)) return fallbackDllPath; // Show where we've looked Console.WriteLine("Cannot find native library: {0}", defaultDllPath); Console.WriteLine("Cannot find native library: {0}", fallbackDllPath); // Fall through to default error handling (i.e. throw FileNotFoundException when trying to load the library) return defaultDllPath; } private static string GetMacOsNativeLibraryPath(string iosSupportPath) { // Native M1 reports as Arm64. Rosetta reports as X64, same as actual Intel X64 if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64) { var dylibPath = Path.Combine(iosSupportPath, NativeDylibOsxArm64); if (!File.Exists(dylibPath) && Directory.Exists(iosSupportPath)) { Console.WriteLine("No Apple Silicon native library available at '{0}'", dylibPath); throw new PlatformNotSupportedException( "Apple Silicon support requires a native install of Unity 2021.2 or above"); } return dylibPath; } var defaultDylibPath = Path.Combine(iosSupportPath, NativeDylibOsxX64); if (File.Exists(defaultDylibPath)) return defaultDylibPath; var fallbackDylibPath = Path.Combine(iosSupportPath, NativeDylibOsxFallback); if (File.Exists(fallbackDylibPath)) return fallbackDylibPath; // Show where we've looked Console.WriteLine("Cannot find native library: {0}", defaultDylibPath); Console.WriteLine("Cannot find native library: {0}", fallbackDylibPath); // Fall through to default error handling (i.e. throw FileNotFoundException when trying to load the library) return defaultDylibPath; } private static string GetLinuxNativeLibraryPath(string iosSupportPath) { if (RuntimeInformation.ProcessArchitecture != Architecture.X64) { throw new PlatformNotSupportedException("No native library for process architecture " + RuntimeInformation.ProcessArchitecture); } var defaultSoPath = Path.Combine(iosSupportPath, NativeSoLinuxX64); if (File.Exists(defaultSoPath)) return defaultSoPath; var fallbackSoPath = Path.Combine(iosSupportPath, NativeSoLinuxX64Fallback); if (File.Exists(fallbackSoPath)) return fallbackSoPath; // Show where we've looked Console.WriteLine("Cannot find native library: {0}", defaultSoPath); Console.WriteLine("Cannot find native library: {0}", fallbackSoPath); // Fall through to default error handling (i.e. throw FileNotFoundException when trying to load the library) return defaultSoPath; } private static void LoadNativeLibrary(string libraryPath) { if (ourNativeLibraryHandle == IntPtr.Zero) { ourNativeLibraryHandle = ourLoader.LoadLibrary(libraryPath); if (ourNativeLibraryHandle != IntPtr.Zero) Console.WriteLine("Loaded: " + libraryPath); else throw new InvalidOperationException("Couldn't load library: " + libraryPath); } } private static void InitFunctions() { StartUsbmuxdListenThread = LoadFunction<StartUsbmuxdListenThreadDelegate>("StartUsbmuxdListenThread"); StopUsbmuxdListenThread = LoadFunction<StopUsbmuxdListenThreadDelegate>("StopUsbmuxdListenThread"); UsbmuxdGetDeviceCount = LoadFunction<UsbmuxdGetDeviceCountDelegate>("UsbmuxdGetDeviceCount"); UsbmuxdGetDevice = LoadFunction<UsbmuxdGetDeviceDelegate>("UsbmuxdGetDevice"); StartIosProxy = LoadFunction<StartIosProxyDelegate>("StartIosProxy"); StopIosProxy = LoadFunction<StopIosProxyDelegate>("StopIosProxy"); } private static TType LoadFunction<TType>(string name) where TType: class { if (ourNativeLibraryHandle == IntPtr.Zero) throw new Exception("iOS native extension library was not loaded"); IntPtr addr = ourLoader.GetProcAddress(ourNativeLibraryHandle, name); return Marshal.GetDelegateForFunctionPointer(addr, typeof(TType)) as TType; } static Usbmuxd() { switch (Environment.OSVersion.Platform) { case PlatformID.Unix: case PlatformID.MacOSX: ourLoader = new PosixDllLoader(); break; case PlatformID.Win32NT: ourLoader = new WindowsDllLoader(); break; default: throw new PlatformNotSupportedException("Platform not supported"); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Umbraco.Core.Models.EntityBase; namespace Umbraco.Core.Events { /// <summary> /// An IEventDispatcher that queues events. /// </summary> /// <remarks> /// <para>Can raise, or ignore, cancelable events, depending on option.</para> /// <para>Implementations must override ScopeExitCompleted to define what /// to do with the events when the scope exits and has been completed.</para> /// <para>If the scope exits without being completed, events are ignored.</para> /// </remarks> public abstract class ScopeEventDispatcherBase : IEventDispatcher { //events will be enlisted in the order they are raised private List<IEventDefinition> _events; private readonly bool _raiseCancelable; protected ScopeEventDispatcherBase(bool raiseCancelable) { _raiseCancelable = raiseCancelable; } private List<IEventDefinition> Events { get { return _events ?? (_events = new List<IEventDefinition>()); } } public bool DispatchCancelable(EventHandler eventHandler, object sender, CancellableEventArgs args, string eventName = null) { if (eventHandler == null) return args.Cancel; if (_raiseCancelable == false) return args.Cancel; eventHandler(sender, args); return args.Cancel; } public bool DispatchCancelable<TArgs>(EventHandler<TArgs> eventHandler, object sender, TArgs args, string eventName = null) where TArgs : CancellableEventArgs { if (eventHandler == null) return args.Cancel; if (_raiseCancelable == false) return args.Cancel; eventHandler(sender, args); return args.Cancel; } public bool DispatchCancelable<TSender, TArgs>(TypedEventHandler<TSender, TArgs> eventHandler, TSender sender, TArgs args, string eventName = null) where TArgs : CancellableEventArgs { if (eventHandler == null) return args.Cancel; if (_raiseCancelable == false) return args.Cancel; eventHandler(sender, args); return args.Cancel; } public void Dispatch(EventHandler eventHandler, object sender, EventArgs args, string eventName = null) { if (eventHandler == null) return; Events.Add(new EventDefinition(eventHandler, sender, args, eventName)); } public void Dispatch<TArgs>(EventHandler<TArgs> eventHandler, object sender, TArgs args, string eventName = null) { if (eventHandler == null) return; Events.Add(new EventDefinition<TArgs>(eventHandler, sender, args, eventName)); } public void Dispatch<TSender, TArgs>(TypedEventHandler<TSender, TArgs> eventHandler, TSender sender, TArgs args, string eventName = null) { if (eventHandler == null) return; Events.Add(new EventDefinition<TSender, TArgs>(eventHandler, sender, args, eventName)); } public IEnumerable<IEventDefinition> GetEvents(EventDefinitionFilter filter) { if (_events == null) return Enumerable.Empty<IEventDefinition>(); IReadOnlyList<IEventDefinition> events; switch (filter) { case EventDefinitionFilter.All: events = _events; break; case EventDefinitionFilter.FirstIn: var l1 = new OrderedHashSet<IEventDefinition>(); foreach (var e in _events) l1.Add(e); events = l1; break; case EventDefinitionFilter.LastIn: var l2 = new OrderedHashSet<IEventDefinition>(keepOldest: false); foreach (var e in _events) l2.Add(e); events = l2; break; default: throw new ArgumentOutOfRangeException("filter", filter, null); } return FilterSupersededAndUpdateToLatestEntity(events); } private class EventDefinitionInfos { public IEventDefinition EventDefinition { get; set; } public Type[] SupersedeTypes { get; set; } } // fixme // this is way too convoluted, the superceede attribute is used only on DeleteEventargs to specify // that it superceeds save, publish, move and copy - BUT - publish event args is also used for // unpublishing and should NOT be superceeded - so really it should not be managed at event args // level but at event level // // what we want is: // if an entity is deleted, then all Saved, Moved, Copied, Published events prior to this should // not trigger for the entity - and even though, does it make any sense? making a copy of an entity // should ... trigger? // // not going to refactor it all - we probably want to *always* trigger event but tell people that // due to scopes, they should not expected eg a saved entity to still be around - however, now, // going to write a ugly condition to deal with U4-10764 // iterates over the events (latest first) and filter out any events or entities in event args that are included // in more recent events that Supersede previous ones. For example, If an Entity has been Saved and then Deleted, we don't want // to raise the Saved event (well actually we just don't want to include it in the args for that saved event) internal static IEnumerable<IEventDefinition> FilterSupersededAndUpdateToLatestEntity(IReadOnlyList<IEventDefinition> events) { // keeps the 'latest' entity and associated event data var entities = new List<Tuple<IEntity, EventDefinitionInfos>>(); // collects the event definitions // collects the arguments in result, that require their entities to be updated var result = new List<IEventDefinition>(); var resultArgs = new List<CancellableObjectEventArgs>(); // eagerly fetch superceeded arg types for each arg type var argTypeSuperceeding = events.Select(x => x.Args.GetType()) .Distinct() .ToDictionary(x => x, x => x.GetCustomAttributes<SupersedeEventAttribute>(false).Select(y => y.SupersededEventArgsType).ToArray()); // iterate over all events and filter // // process the list in reverse, because events are added in the order they are raised and we want to keep // the latest (most recent) entities and filter out what is not relevant anymore (too old), eg if an entity // is Deleted after being Saved, we want to filter out the Saved event for (var index = events.Count - 1; index >= 0; index--) { var def = events[index]; var infos = new EventDefinitionInfos { EventDefinition = def, SupersedeTypes = argTypeSuperceeding[def.Args.GetType()] }; var args = def.Args as CancellableObjectEventArgs; if (args == null) { // not a cancellable event arg, include event definition in result result.Add(def); } else { // event object can either be a single object or an enumerable of objects // try to get as an enumerable, get null if it's not var eventObjects = TypeHelper.CreateGenericEnumerableFromObject(args.EventObject); if (eventObjects == null) { // single object, cast as an IEntity // if cannot cast, cannot filter, nothing - just include event definition in result var eventEntity = args.EventObject as IEntity; if (eventEntity == null) { result.Add(def); continue; } // look for this entity in superceding event args // found = must be removed (ie not added), else track if (IsSuperceeded(eventEntity, infos, entities) == false) { // track entities.Add(Tuple.Create(eventEntity, infos)); // track result arguments // include event definition in result resultArgs.Add(args); result.Add(def); } } else { // enumerable of objects var toRemove = new List<IEntity>(); foreach (var eventObject in eventObjects) { // extract the event object, cast as an IEntity // if cannot cast, cannot filter, nothing to do - just leave it in the list & continue var eventEntity = eventObject as IEntity; if (eventEntity == null) continue; // look for this entity in superceding event args // found = must be removed, else track if (IsSuperceeded(eventEntity, infos, entities)) toRemove.Add(eventEntity); else entities.Add(Tuple.Create(eventEntity, infos)); } // remove superceded entities foreach (var entity in toRemove) eventObjects.Remove(entity); // if there are still entities in the list, keep the event definition if (eventObjects.Count > 0) { if (toRemove.Count > 0) { // re-assign if changed args.EventObject = eventObjects; } // track result arguments // include event definition in result resultArgs.Add(args); result.Add(def); } } } } // go over all args in result, and update them with the latest instanceof each entity UpdateToLatestEntities(entities, resultArgs); // reverse, since we processed the list in reverse result.Reverse(); return result; } // edits event args to use the latest instance of each entity private static void UpdateToLatestEntities(IEnumerable<Tuple<IEntity, EventDefinitionInfos>> entities, IEnumerable<CancellableObjectEventArgs> args) { // get the latest entities // ordered hash set + keepOldest will keep the latest inserted entity (in case of duplicates) var latestEntities = new OrderedHashSet<IEntity>(keepOldest: true); foreach (var entity in entities.OrderByDescending(entity => entity.Item1.UpdateDate)) latestEntities.Add(entity.Item1); foreach (var arg in args) { // event object can either be a single object or an enumerable of objects // try to get as an enumerable, get null if it's not var eventObjects = TypeHelper.CreateGenericEnumerableFromObject(arg.EventObject); if (eventObjects == null) { // single object // look for a more recent entity for that object, and replace if any // works by "equalling" entities ie the more recent one "equals" this one (though different object) var foundEntity = latestEntities.FirstOrDefault(x => Equals(x, arg.EventObject)); if (foundEntity != null) arg.EventObject = foundEntity; } else { // enumerable of objects // same as above but for each object var updated = false; for (var i = 0; i < eventObjects.Count; i++) { var foundEntity = latestEntities.FirstOrDefault(x => Equals(x, eventObjects[i])); if (foundEntity == null) continue; eventObjects[i] = foundEntity; updated = true; } if (updated) arg.EventObject = eventObjects; } } } // determines if a given entity, appearing in a given event definition, should be filtered out, // considering the entities that have already been visited - an entity is filtered out if it // appears in another even definition, which superceedes this event definition. private static bool IsSuperceeded(IEntity entity, EventDefinitionInfos infos, List<Tuple<IEntity, EventDefinitionInfos>> entities) { //var argType = meta.EventArgsType; var argType = infos.EventDefinition.Args.GetType(); // look for other instances of the same entity, coming from an event args that supercedes other event args, // ie is marked with the attribute, and is not this event args (cannot supersede itself) var superceeding = entities .Where(x => x.Item2.SupersedeTypes.Length > 0 // has the attribute && x.Item2.EventDefinition.Args.GetType() != argType // is not the same && Equals(x.Item1, entity)) // same entity .ToArray(); // first time we see this entity = not filtered if (superceeding.Length == 0) return false; // fixme see notes above // delete event args does NOT superceedes 'unpublished' event if (argType.IsGenericType && argType.GetGenericTypeDefinition() == typeof(PublishEventArgs<>) && infos.EventDefinition.EventName == "UnPublished") return false; // found occurences, need to determine if this event args is superceded if (argType.IsGenericType) { // generic, must compare type arguments var supercededBy = superceeding.FirstOrDefault(x => x.Item2.SupersedeTypes.Any(y => // superceeding a generic type which has the same generic type definition // fixme no matter the generic type parameters? could be different? y.IsGenericTypeDefinition && y == argType.GetGenericTypeDefinition() // or superceeding a non-generic type which is ... fixme how is this ever possible? argType *is* generic? || y.IsGenericTypeDefinition == false && y == argType)); return supercededBy != null; } else { // non-generic, can compare types 1:1 var supercededBy = superceeding.FirstOrDefault(x => x.Item2.SupersedeTypes.Any(y => y == argType)); return supercededBy != null; } } public void ScopeExit(bool completed) { if (_events == null) return; if (completed) ScopeExitCompleted(); _events.Clear(); } protected abstract void ScopeExitCompleted(); } }
// 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.Xml; using System.Xml.Schema; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Reflection; namespace System.Xml.Xsl { /// <summary> /// Implementation of read-only IList and IList{T} interfaces. Derived classes can inherit from /// this class and implement only two methods, Count and Item, rather than the entire IList interface. /// </summary> internal abstract class ListBase<T> : IList<T>, System.Collections.IList { //----------------------------------------------- // Abstract IList methods that must be // implemented by derived classes //----------------------------------------------- public abstract int Count { get; } public abstract T this[int index] { get; set; } //----------------------------------------------- // Implemented by base class -- accessible on // ListBase //----------------------------------------------- public virtual bool Contains(T value) { return IndexOf(value) != -1; } public virtual int IndexOf(T value) { for (int i = 0; i < Count; i++) if (value.Equals(this[i])) return i; return -1; } public virtual void CopyTo(T[] array, int index) { for (int i = 0; i < Count; i++) array[index + i] = this[i]; } public virtual IListEnumerator<T> GetEnumerator() { return new IListEnumerator<T>(this); } public virtual bool IsFixedSize { get { return true; } } public virtual bool IsReadOnly { get { return true; } } public virtual void Add(T value) { Insert(Count, value); } public virtual void Insert(int index, T value) { throw new NotSupportedException(); } public virtual bool Remove(T value) { int index = IndexOf(value); if (index >= 0) { RemoveAt(index); return true; } return false; } public virtual void RemoveAt(int index) { throw new NotSupportedException(); } public virtual void Clear() { for (int index = Count - 1; index >= 0; index--) RemoveAt(index); } //----------------------------------------------- // Implemented by base class -- only accessible // after casting to IList //----------------------------------------------- IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new IListEnumerator<T>(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new IListEnumerator<T>(this); } bool System.Collections.ICollection.IsSynchronized { get { return IsReadOnly; } } object System.Collections.ICollection.SyncRoot { get { return this; } } void System.Collections.ICollection.CopyTo(Array array, int index) { for (int i = 0; i < Count; i++) array.SetValue(this[i], index); } object System.Collections.IList.this[int index] { get { return this[index]; } set { if (!IsCompatibleType(value.GetType())) throw new ArgumentException(SR.Arg_IncompatibleParamType, nameof(value)); this[index] = (T)value; } } int System.Collections.IList.Add(object value) { if (!IsCompatibleType(value.GetType())) throw new ArgumentException(SR.Arg_IncompatibleParamType, nameof(value)); Add((T)value); return Count - 1; } void System.Collections.IList.Clear() { Clear(); } bool System.Collections.IList.Contains(object value) { if (!IsCompatibleType(value.GetType())) return false; return Contains((T)value); } int System.Collections.IList.IndexOf(object value) { if (!IsCompatibleType(value.GetType())) return -1; return IndexOf((T)value); } void System.Collections.IList.Insert(int index, object value) { if (!IsCompatibleType(value.GetType())) throw new ArgumentException(SR.Arg_IncompatibleParamType, nameof(value)); Insert(index, (T)value); } void System.Collections.IList.Remove(object value) { if (IsCompatibleType(value.GetType())) { Remove((T)value); } } //----------------------------------------------- // Helper methods and classes //----------------------------------------------- private static bool IsCompatibleType(object value) { if ((value == null && !typeof(T).IsValueType) || (value is T)) return true; return false; } } /// <summary> /// Implementation of IEnumerator{T} and IEnumerator over an IList{T}. /// </summary> internal struct IListEnumerator<T> : IEnumerator<T>, System.Collections.IEnumerator { private readonly IList<T> _sequence; private int _index; private T _current; /// <summary> /// Constructor. /// </summary> public IListEnumerator(IList<T> sequence) { _sequence = sequence; _index = 0; _current = default(T); } /// <summary> /// No-op. /// </summary> public void Dispose() { } /// <summary> /// Return current item. Return default value if before first item or after last item in the list. /// </summary> public T Current { get { return _current; } } /// <summary> /// Return current item. Throw exception if before first item or after last item in the list. /// </summary> object System.Collections.IEnumerator.Current { get { if (_index == 0) throw new InvalidOperationException(SR.Format(SR.Sch_EnumNotStarted, string.Empty)); if (_index > _sequence.Count) throw new InvalidOperationException(SR.Format(SR.Sch_EnumFinished, string.Empty)); return _current; } } /// <summary> /// Advance enumerator to next item in list. Return false if there are no more items. /// </summary> public bool MoveNext() { if (_index < _sequence.Count) { _current = _sequence[_index]; _index++; return true; } _current = default(T); return false; } /// <summary> /// Set the enumerator to its initial position, which is before the first item in the list. /// </summary> void System.Collections.IEnumerator.Reset() { _index = 0; _current = default(T); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.IO; using System.Runtime; using System.Runtime.Serialization; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using Microsoft.Xml; namespace System.ServiceModel.Channels { public abstract class MessageHeader : MessageHeaderInfo { private const bool DefaultRelayValue = false; private const bool DefaultMustUnderstandValue = false; private const string DefaultActorValue = ""; public override string Actor { get { return ""; } } public override bool IsReferenceParameter { get { return false; } } public override bool MustUnderstand { get { return DefaultMustUnderstandValue; } } public override bool Relay { get { return DefaultRelayValue; } } public virtual bool IsMessageVersionSupported(MessageVersion messageVersion) { if (messageVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion"); } return true; } public override string ToString() { XmlWriterSettings xmlSettings = new XmlWriterSettings() { Indent = true }; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { using (XmlWriter textWriter = XmlWriter.Create(stringWriter, xmlSettings)) { using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(textWriter)) { if (IsMessageVersionSupported(MessageVersion.Soap12WSAddressing10)) { WriteHeader(writer, MessageVersion.Soap12WSAddressing10); } else if (IsMessageVersionSupported(MessageVersion.Soap11WSAddressing10)) { WriteHeader(writer, MessageVersion.Soap11WSAddressing10); } else if (IsMessageVersionSupported(MessageVersion.Soap12)) { WriteHeader(writer, MessageVersion.Soap12); } else if (IsMessageVersionSupported(MessageVersion.Soap11)) { WriteHeader(writer, MessageVersion.Soap11); } else { WriteHeader(writer, MessageVersion.None); } writer.Flush(); return stringWriter.ToString(); } } } } public void WriteHeader(XmlWriter writer, MessageVersion messageVersion) { WriteHeader(XmlDictionaryWriter.CreateDictionaryWriter(writer), messageVersion); } public void WriteHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { if (writer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer")); if (messageVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion")); OnWriteStartHeader(writer, messageVersion); OnWriteHeaderContents(writer, messageVersion); writer.WriteEndElement(); } public void WriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { if (writer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer")); if (messageVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion")); OnWriteStartHeader(writer, messageVersion); } protected virtual void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteStartElement(this.Name, this.Namespace); WriteHeaderAttributes(writer, messageVersion); } public void WriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { if (writer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer")); if (messageVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion")); OnWriteHeaderContents(writer, messageVersion); } protected abstract void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion); protected void WriteHeaderAttributes(XmlDictionaryWriter writer, MessageVersion messageVersion) { string actor = this.Actor; if (actor.Length > 0) writer.WriteAttributeString(messageVersion.Envelope.DictionaryActor, messageVersion.Envelope.DictionaryNamespace, actor); if (this.MustUnderstand) writer.WriteAttributeString(XD.MessageDictionary.MustUnderstand, messageVersion.Envelope.DictionaryNamespace, "1"); if (this.Relay && messageVersion.Envelope == EnvelopeVersion.Soap12) writer.WriteAttributeString(XD.Message12Dictionary.Relay, XD.Message12Dictionary.Namespace, "1"); } public static MessageHeader CreateHeader(string name, string ns, object value) { return CreateHeader(name, ns, value, DefaultMustUnderstandValue, DefaultActorValue, DefaultRelayValue); } public static MessageHeader CreateHeader(string name, string ns, object value, bool mustUnderstand) { return CreateHeader(name, ns, value, mustUnderstand, DefaultActorValue, DefaultRelayValue); } public static MessageHeader CreateHeader(string name, string ns, object value, bool mustUnderstand, string actor) { return CreateHeader(name, ns, value, mustUnderstand, actor, DefaultRelayValue); } public static MessageHeader CreateHeader(string name, string ns, object value, bool mustUnderstand, string actor, bool relay) { return new XmlObjectSerializerHeader(name, ns, value, null, mustUnderstand, actor, relay); } public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer) { return CreateHeader(name, ns, value, serializer, DefaultMustUnderstandValue, DefaultActorValue, DefaultRelayValue); } public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer, bool mustUnderstand) { return CreateHeader(name, ns, value, serializer, mustUnderstand, DefaultActorValue, DefaultRelayValue); } public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer, bool mustUnderstand, string actor) { return CreateHeader(name, ns, value, serializer, mustUnderstand, actor, DefaultRelayValue); } public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay) { if (serializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer")); return new XmlObjectSerializerHeader(name, ns, value, serializer, mustUnderstand, actor, relay); } internal static void GetHeaderAttributes(XmlDictionaryReader reader, MessageVersion version, out string actor, out bool mustUnderstand, out bool relay, out bool isReferenceParameter) { int attributeCount = reader.AttributeCount; if (attributeCount == 0) { mustUnderstand = false; actor = string.Empty; relay = false; isReferenceParameter = false; } else { string mustUnderstandString = reader.GetAttribute(XD.MessageDictionary.MustUnderstand, version.Envelope.DictionaryNamespace); if (mustUnderstandString != null && ToBoolean(mustUnderstandString)) mustUnderstand = true; else mustUnderstand = false; if (mustUnderstand && attributeCount == 1) { actor = string.Empty; relay = false; } else { actor = reader.GetAttribute(version.Envelope.DictionaryActor, version.Envelope.DictionaryNamespace); if (actor == null) actor = ""; if (version.Envelope == EnvelopeVersion.Soap12) { string relayString = reader.GetAttribute(XD.Message12Dictionary.Relay, version.Envelope.DictionaryNamespace); if (relayString != null && ToBoolean(relayString)) relay = true; else relay = false; } else { relay = false; } } isReferenceParameter = false; if (version.Addressing == AddressingVersion.WSAddressing10) { string refParam = reader.GetAttribute(XD.AddressingDictionary.IsReferenceParameter, version.Addressing.DictionaryNamespace); if (refParam != null) isReferenceParameter = ToBoolean(refParam); } } } private static bool ToBoolean(string value) { if (value.Length == 1) { char ch = value[0]; if (ch == '1') { return true; } if (ch == '0') { return false; } } else { if (value == "true") { return true; } else if (value == "false") { return false; } } try { return XmlConvert.ToBoolean(value); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(exception.Message, (Exception)null)); } } } internal abstract class DictionaryHeader : MessageHeader { public override string Name { get { return DictionaryName.Value; } } public override string Namespace { get { return DictionaryNamespace.Value; } } public abstract XmlDictionaryString DictionaryName { get; } public abstract XmlDictionaryString DictionaryNamespace { get; } protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteStartElement(DictionaryName, DictionaryNamespace); WriteHeaderAttributes(writer, messageVersion); } } internal class XmlObjectSerializerHeader : MessageHeader { private XmlObjectSerializer _serializer; private bool _mustUnderstand; private bool _relay; private bool _isOneTwoSupported; private bool _isOneOneSupported; private bool _isNoneSupported; private object _objectToSerialize; private string _name; private string _ns; private string _actor; private object _syncRoot = new object(); private XmlObjectSerializerHeader(XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay) { if (actor == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("actor"); } _mustUnderstand = mustUnderstand; _relay = relay; _serializer = serializer; _actor = actor; if (actor == EnvelopeVersion.Soap12.UltimateDestinationActor) { _isOneOneSupported = false; _isOneTwoSupported = true; } else if (actor == EnvelopeVersion.Soap12.NextDestinationActorValue) { _isOneOneSupported = false; _isOneTwoSupported = true; } else if (actor == EnvelopeVersion.Soap11.NextDestinationActorValue) { _isOneOneSupported = true; _isOneTwoSupported = false; } else { _isOneOneSupported = true; _isOneTwoSupported = true; _isNoneSupported = true; } } public XmlObjectSerializerHeader(string name, string ns, object objectToSerialize, XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay) : this(serializer, mustUnderstand, actor, relay) { if (null == name) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name")); } if (name.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SRServiceModel.SFXHeaderNameCannotBeNullOrEmpty, "name")); } if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns"); } if (ns.Length > 0) { NamingHelper.CheckUriParameter(ns, "ns"); } _objectToSerialize = objectToSerialize; _name = name; _ns = ns; } public override bool IsMessageVersionSupported(MessageVersion messageVersion) { if (messageVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion"); } if (messageVersion.Envelope == EnvelopeVersion.Soap12) { return _isOneTwoSupported; } else if (messageVersion.Envelope == EnvelopeVersion.Soap11) { return _isOneOneSupported; } else if (messageVersion.Envelope == EnvelopeVersion.None) { return _isNoneSupported; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.EnvelopeVersionUnknown, messageVersion.Envelope.ToString()))); } } public override string Name { get { return _name; } } public override string Namespace { get { return _ns; } } public override bool MustUnderstand { get { return _mustUnderstand; } } public override bool Relay { get { return _relay; } } public override string Actor { get { return _actor; } } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { lock (_syncRoot) { if (_serializer == null) { _serializer = DataContractSerializerDefaults.CreateSerializer( (_objectToSerialize == null ? typeof(object) : _objectToSerialize.GetType()), this.Name, this.Namespace, int.MaxValue/*maxItems*/); } _serializer.WriteObjectContent(writer, _objectToSerialize); } } } internal abstract class ReadableMessageHeader : MessageHeader { public abstract XmlDictionaryReader GetHeaderReader(); protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { if (!IsMessageVersionSupported(messageVersion)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(string.Format(SRServiceModel.MessageHeaderVersionNotSupported, this.GetType().FullName, messageVersion.ToString()), "version")); XmlDictionaryReader reader = GetHeaderReader(); writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); writer.WriteAttributes(reader, false); reader.Dispose(); } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { XmlDictionaryReader reader = GetHeaderReader(); reader.ReadStartElement(); while (reader.NodeType != XmlNodeType.EndElement) writer.WriteNode(reader, false); reader.ReadEndElement(); reader.Dispose(); } } internal interface IMessageHeaderWithSharedNamespace { XmlDictionaryString SharedNamespace { get; } XmlDictionaryString SharedPrefix { get; } } internal class BufferedHeader : ReadableMessageHeader { private MessageVersion _version; private XmlBuffer _buffer; private int _bufferIndex; private string _actor; private bool _relay; private bool _mustUnderstand; private string _name; private string _ns; private bool _streamed; private bool _isRefParam; public BufferedHeader(MessageVersion version, XmlBuffer buffer, int bufferIndex, string name, string ns, bool mustUnderstand, string actor, bool relay, bool isRefParam) { _version = version; _buffer = buffer; _bufferIndex = bufferIndex; _name = name; _ns = ns; _mustUnderstand = mustUnderstand; _actor = actor; _relay = relay; _isRefParam = isRefParam; } public BufferedHeader(MessageVersion version, XmlBuffer buffer, int bufferIndex, MessageHeaderInfo headerInfo) { _version = version; _buffer = buffer; _bufferIndex = bufferIndex; _actor = headerInfo.Actor; _relay = headerInfo.Relay; _name = headerInfo.Name; _ns = headerInfo.Namespace; _isRefParam = headerInfo.IsReferenceParameter; _mustUnderstand = headerInfo.MustUnderstand; } public BufferedHeader(MessageVersion version, XmlBuffer buffer, XmlDictionaryReader reader, XmlAttributeHolder[] envelopeAttributes, XmlAttributeHolder[] headerAttributes) { _streamed = true; _buffer = buffer; _version = version; GetHeaderAttributes(reader, version, out _actor, out _mustUnderstand, out _relay, out _isRefParam); _name = reader.LocalName; _ns = reader.NamespaceURI; Fx.Assert(_name != null, ""); Fx.Assert(_ns != null, ""); _bufferIndex = buffer.SectionCount; XmlDictionaryWriter writer = buffer.OpenSection(reader.Quotas); // Write an enclosing Envelope tag writer.WriteStartElement(MessageStrings.Envelope); if (envelopeAttributes != null) XmlAttributeHolder.WriteAttributes(envelopeAttributes, writer); // Write and enclosing Header tag writer.WriteStartElement(MessageStrings.Header); if (headerAttributes != null) XmlAttributeHolder.WriteAttributes(headerAttributes, writer); writer.WriteNode(reader, false); writer.WriteEndElement(); writer.WriteEndElement(); buffer.CloseSection(); } public override string Actor { get { return _actor; } } public override bool IsReferenceParameter { get { return _isRefParam; } } public override string Name { get { return _name; } } public override string Namespace { get { return _ns; } } public override bool MustUnderstand { get { return _mustUnderstand; } } public override bool Relay { get { return _relay; } } public override bool IsMessageVersionSupported(MessageVersion messageVersion) { if (messageVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion")); return messageVersion == _version; } public override XmlDictionaryReader GetHeaderReader() { XmlDictionaryReader reader = _buffer.GetReader(_bufferIndex); // See if we need to move past the enclosing envelope/header if (_streamed) { reader.MoveToContent(); reader.Read(); // Envelope reader.Read(); // Header reader.MoveToContent(); } return reader; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.IO.Tests { public class File_Create_str : FileSystemTest { #region Utilities public virtual FileStream Create(string path) { return File.Create(path); } #endregion #region UniversalTests [Fact] public void NullPath() { Assert.Throws<ArgumentNullException>(() => Create(null)); } [Fact] public void EmptyPath() { Assert.Throws<ArgumentException>(() => Create(string.Empty)); } [Fact] public void NonExistentPath() { Assert.Throws<DirectoryNotFoundException>(() => Create(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()))); } [Fact] public void CreateCurrentDirectory() { Assert.Throws<UnauthorizedAccessException>(() => Create(".")); } [Fact] public void ValidCreation() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Equal(0, stream.Length); Assert.Equal(0, stream.Position); } } [ConditionalFact(nameof(UsingNewNormalization))] [PlatformSpecific(TestPlatforms.Windows)] // Valid Windows path extended prefix public void ValidCreation_ExtendedSyntax() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); Assert.StartsWith(IOInputs.ExtendedPrefix, testDir.FullName); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Equal(0, stream.Length); Assert.Equal(0, stream.Position); } } [ConditionalFact(nameof(AreAllLongPathsAvailable))] [PlatformSpecific(TestPlatforms.Windows)] // Valid Windows path extended prefix, long path public void ValidCreation_LongPathExtendedSyntax() { DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500)); Assert.StartsWith(IOInputs.ExtendedPrefix, testDir.FullName); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Equal(0, stream.Length); Assert.Equal(0, stream.Position); } } [Fact] public void CreateInParentDirectory() { string testFile = GetTestFileName(); using (FileStream stream = Create(Path.Combine(TestDirectory, "DoesntExists", "..", testFile))) { Assert.True(File.Exists(Path.Combine(TestDirectory, testFile))); } } [Fact] public void LegalSymbols() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName() + "!@#$%^&"); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); } } [Fact] public void InvalidDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName(), GetTestFileName()); Assert.Throws<DirectoryNotFoundException>(() => Create(testFile)); } [Fact] public void FileInUse() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Throws<IOException>(() => Create(testFile)); } } [Fact] public void FileAlreadyExists() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); } [Fact] public void OverwriteReadOnly() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); } [Fact] public void LongPathSegment() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); // Long path should throw PathTooLongException on Desktop and IOException // elsewhere. if (PlatformDetection.IsFullFramework) { Assert.Throws<PathTooLongException>( () => Create(Path.Combine(testDir.FullName, new string('a', 300)))); } else { AssertExtensions.ThrowsAny<IOException, DirectoryNotFoundException, PathTooLongException>( () => Create(Path.Combine(testDir.FullName, new string('a', 300)))); } } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(CaseSensitivePlatforms)] public void CaseSensitive() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (File.Create(testFile + "AAAA")) using (File.Create(testFile + "aAAa")) { Assert.False(File.Exists(testFile + "AaAa")); Assert.True(File.Exists(testFile + "AAAA")); Assert.True(File.Exists(testFile + "aAAa")); Assert.Equal(2, Directory.GetFiles(testDir.FullName).Length); } Assert.Throws<DirectoryNotFoundException>(() => File.Create(testFile.ToLowerInvariant())); } [Fact] [PlatformSpecific(CaseInsensitivePlatforms)] public void CaseInsensitive() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); File.Create(testFile + "AAAA").Dispose(); File.Create(testFile.ToLowerInvariant() + "aAAa").Dispose(); Assert.Equal(1, Directory.GetFiles(testDir.FullName).Length); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Invalid file name with wildcard characters on Windows public void WindowsWildCharacterPath() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "dls;d", "442349-0", "v443094(*)(+*$#$*", new string(Path.DirectorySeparatorChar, 3)))); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "*"))); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "Test*t"))); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "*Tes*t"))); } [Theory, InlineData(" "), InlineData(" "), InlineData("\n"), InlineData(">"), InlineData("<"), InlineData("\0"), InlineData("\t")] [PlatformSpecific(TestPlatforms.Windows)] // Invalid file name with whitespace on Windows public void WindowsWhitespacePath(string path) { Assert.Throws<ArgumentException>(() => Create(path)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void CreateNullThrows_Unix() { Assert.Throws<ArgumentException>(() => Create("\0")); } [Theory, InlineData(" "), InlineData(" "), InlineData("\n"), InlineData(">"), InlineData("<"), InlineData("\t")] [PlatformSpecific(TestPlatforms.AnyUnix)] // Valid file name with Whitespace on Unix public void UnixWhitespacePath(string path) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); using (Create(Path.Combine(testDir.FullName, path))) { Assert.True(File.Exists(Path.Combine(testDir.FullName, path))); } } #endregion } public class File_Create_str_i : File_Create_str { public override FileStream Create(string path) { return File.Create(path, 4096); // Default buffer size } public virtual FileStream Create(string path, int bufferSize) { return File.Create(path, bufferSize); } [Fact] public void NegativeBuffer() { Assert.Throws<ArgumentOutOfRangeException>(() => Create(GetTestFilePath(), -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Create(GetTestFilePath(), -100)); } } public class File_Create_str_i_fo : File_Create_str_i { public override FileStream Create(string path) { return File.Create(path, 4096, FileOptions.Asynchronous); } public override FileStream Create(string path, int bufferSize) { return File.Create(path, bufferSize, FileOptions.Asynchronous); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.AppService.Fluent { using AppServiceDomain.Definition; using AppServiceDomain.Update; using Models; using ResourceManager.Fluent; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; /// <summary> /// The implementation for AppServiceDomain. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmFwcHNlcnZpY2UuaW1wbGVtZW50YXRpb24uQXBwU2VydmljZURvbWFpbkltcGw= internal partial class AppServiceDomainImpl : GroupableResource< IAppServiceDomain, DomainInner, AppServiceDomainImpl, IAppServiceManager, IBlank, IWithRegistrantContact, IWithCreate, IUpdate>, IAppServiceDomain, IDefinition, IUpdate { private IDictionary<string, HostName> hostNameMap; private string clientIp = "127.0.0.1"; ///GENMHASH:E3A506AB29CB79E19BE35E770B4C876E:E11180BB79B722174FB3D0453FCEA12B public DomainStatus RegistrationStatus() { return Inner.RegistrationStatus.GetValueOrDefault(); } ///GENMHASH:CD48C699C847906F9DDB2B020855A2B4:7B32ADCF145314E68A75089E358F8048 public IReadOnlyDictionary<string, HostName> ManagedHostNames() { if (hostNameMap == null) { return null; } return new ReadOnlyDictionary<string, HostName>(hostNameMap); } ///GENMHASH:B325C6EDB78E19FA38381AFEBE68C699:93880789C7D7BC998F830F0430AFDE23 public AppServiceDomainImpl WithRegistrantContact(Contact contact) { Inner.ContactAdmin = contact; Inner.ContactBilling = contact; Inner.ContactRegistrant = contact; Inner.ContactTech = contact; return this; } ///GENMHASH:2EBE0E253F1D6DB178F3433FF5310EA8:62D7374C9C52BDCC93D26784CA76AFA8 public IReadOnlyList<string> NameServers() { return Inner.NameServers?.ToList(); } ///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:90FEC55929748850F1ED324D0CB61EE7 public async override Task<Microsoft.Azure.Management.AppService.Fluent.IAppServiceDomain> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken)) { string[] domainParts = this.Name.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries); string topLevel = domainParts[domainParts.Length - 1]; // Step 1: Consent to agreements var agreements = await Manager.Inner.TopLevelDomains.ListAgreementsAsync(topLevel, new TopLevelDomainAgreementOption()); var agreementKeys = agreements.Select(x => x.AgreementKey).ToList(); // Step 2: Create domain Inner.Consent = new DomainPurchaseConsent() { AgreedAt = new DateTime(), AgreedBy = clientIp, AgreementKeys = agreementKeys }; SetInner(await Manager.Inner.Domains.CreateOrUpdateAsync(ResourceGroupName, Name, Inner)); return this; } ///GENMHASH:AE0056570274B48455DD7ACC9F27A81F:3E3B7D06869575F5C78E35CCAC61756F public AppServiceDomainImpl WithAdminContact(Contact contact) { Inner.ContactAdmin = contact; return this; } ///GENMHASH:DAD6DB3EAC6CE818886AEBBFB00CE7A8:401E0ADD8B6219F6D6984409E5C6ED31 public Contact BillingContact() { return Inner.ContactBilling; } ///GENMHASH:25ECBB91358E945934523C6618D3A175:9790BA604E44527A0ACFB87F8D1F3432 public AppServiceDomainImpl WithBillingContact(Contact contact) { Inner.ContactBilling = contact; return this; } ///GENMHASH:86C009804770AC54F0EF700492B5521A:3F31672F95C70228EC68BAF9D885F605 internal AppServiceDomainImpl(string name, DomainInner innerObject, IAppServiceManager manager) : base(name, innerObject, manager) { Inner.Location = "global"; if (Inner.ManagedHostNames != null) { hostNameMap = Inner.ManagedHostNames.ToDictionary(h => h.Name); } } ///GENMHASH:B023ACEE2E8E886E8EC94C82F6C93544:19266588ED73C70479B22B9357256AED public bool ReadyForDnsRecordManagement() { return Inner.ReadyForDnsRecordManagement.GetValueOrDefault(); } ///GENMHASH:CC6E0592F0BCD4CD83D832B40167E562:19BB8B1526082C9526EBBE504AC24AE2 public async Task VerifyDomainOwnershipAsync(string certificateOrderName, string domainVerificationToken, CancellationToken cancellationToken = default(CancellationToken)) { DomainOwnershipIdentifierInner identifierInner = new DomainOwnershipIdentifierInner() { OwnershipId = domainVerificationToken }; await Manager.Inner.Domains.CreateOrUpdateOwnershipIdentifierAsync(ResourceGroupName, Name, certificateOrderName, identifierInner, cancellationToken); } ///GENMHASH:EE3A4FAA12095D4EBD752C6D82325EDA:DD8B0DBE8A8402002F39ECC61A75D5BE public Contact RegistrantContact() { return Inner.ContactRegistrant; } ///GENMHASH:4002186478A1CB0B59732EBFB18DEB3A:24635E3B6AB96D3E6BFB9DA2AF7C6AB5 protected override async Task<DomainInner> GetInnerAsync(CancellationToken cancellationToken) { return await Manager.Inner.Domains.GetAsync(ResourceGroupName, Name, cancellationToken: cancellationToken); } ///GENMHASH:F68B7C06A96EFE50420CFD0AF40077FB:26EA9A37169A3648217216A1F31DE87A public Contact AdminContact() { return Inner.ContactAdmin; } ///GENMHASH:7EDAD5E463253CD91487112D769E5CEB:EDF3C8E01B8C87E9F1967C7BA6AA29AF public AppServiceDomainImpl WithDomainPrivacyEnabled(bool domainPrivacy) { Inner.Privacy = domainPrivacy; return this; } ///GENMHASH:7DBBDC25F58D466AD09403C212DD85DF:CECEB118A3DA0C515FB74BE0D6D9C14C public Contact TechContact() { return Inner.ContactTech; } ///GENMHASH:809F7C2A470541FEE2E6E71AB92C8FFC:88752E3558468515A86B34901E5EF9BF public DomainPurchaseConsent Consent() { return Inner.Consent; } ///GENMHASH:5995F84711525BE1DF7039D80FA0DB81:FD36CC16B0F887062F41FE2350D0730E public DateTime CreatedTime() { return Inner.CreatedTime.GetValueOrDefault(); } ///GENMHASH:DBA6815EBA79F0E01B35956CD8DCD5A2:C1913678BBD6634C7B4E02B1C3F7F9BE public bool Privacy() { return Inner.Privacy.GetValueOrDefault(); } ///GENMHASH:41623473E4BF423028E4B08F2C4942DB:917E448810EBA2D53E9DC69100F474BB public DateTime LastRenewedTime() { return Inner.LastRenewedTime.GetValueOrDefault(); } ///GENMHASH:BA6FE1E2B7314E708853F2FBB27E3384:14CF3EB6F5E6911BFEE7C598E534E063 public bool AutoRenew() { return Inner.AutoRenew.GetValueOrDefault(); } ///GENMHASH:2ABF2C4DD400A4212AE592552C6810E4:D4B087937E8FB132F99CE79CA3F74A48 public AppServiceDomainImpl WithAutoRenewEnabled(bool autoRenew) { Inner.AutoRenew = autoRenew; return this; } ///GENMHASH:EB8C33DACE377CBB07C354F38C5BEA32:40B9A5AF5E2BAAC912A2E077A8B03C22 public void VerifyDomainOwnership(string certificateOrderName, string domainVerificationToken) { Extensions.Synchronize(() => VerifyDomainOwnershipAsync(certificateOrderName, domainVerificationToken)); } ///GENMHASH:5CD8F39F706EAB04A535707B7DF3A013:718ADC376CD7CA3987522D4C1A280D4D public AppServiceDomainImpl WithTechContact(Contact contact) { Inner.ContactTech = contact; return this; } ///GENMHASH:4832496C4642B084507B2963F8963228:8BAA92C0EB2A8A25AC36BC01E781F9F7 public DateTime ExpirationTime() { return Inner.ExpirationTime.GetValueOrDefault(); } ///GENMHASH:9E263F72C0A5B9EBC6A0238B83B03A67:7ECFE1750E97BCA44690E1A7698CEB5F public DomainContactImpl DefineRegistrantContact() { return new DomainContactImpl(new Contact(), this); } public IWithCreate WithClientIpAddress(string ipAddress) { clientIp = ipAddress; return this; } } }
// 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.Composition; using System.Diagnostics; using System.IO; using System.IO.MemoryMappedFiles; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Host), Shared] internal partial class TemporaryStorageServiceFactory : IWorkspaceServiceFactory { public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { var textFactory = workspaceServices.GetService<ITextFactoryService>(); return new TemporaryStorageService(textFactory); } /// <summary> /// Temporarily stores text and streams in memory mapped files. /// </summary> internal class TemporaryStorageService : ITemporaryStorageService2 { /// <summary> /// The maximum size in bytes of a single storage unit in a memory mapped file which is shared with other /// storage units. /// </summary> /// <remarks> /// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests /// something better.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private const long SingleFileThreshold = 128 * 1024; /// <summary> /// The size in bytes of a memory mapped file created to store multiple temporary objects. /// </summary> /// <remarks> /// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests /// something better.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private const long MultiFileBlockSize = SingleFileThreshold * 32; private readonly ITextFactoryService _textFactory; /// <summary> /// The synchronization object for accessing the memory mapped file related fields (indicated in the remarks /// of each field). /// </summary> /// <remarks> /// <para>PERF DEV NOTE: A concurrent (but complex) implementation of this type with identical semantics is /// available in source control history. The use of exclusive locks was not causing any measurable /// performance overhead even on 28-thread machines at the time this was written.</para> /// </remarks> private readonly object _gate = new object(); /// <summary> /// The most recent memory mapped file for creating multiple storage units. It will be used via bump-pointer /// allocation until space is no longer available in it. /// </summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> private ReferenceCountedDisposable<MemoryMappedFile>.WeakReference _weakFileReference; /// <summary>The name of the current memory mapped file for multiple storage units.</summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private string _name; /// <summary>The total size of the current memory mapped file for multiple storage units.</summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private long _fileSize; /// <summary> /// The offset into the current memory mapped file where the next storage unit can be held. /// </summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private long _offset; public TemporaryStorageService(ITextFactoryService textFactory) { _textFactory = textFactory; } public ITemporaryTextStorage CreateTemporaryTextStorage(CancellationToken cancellationToken) { return new TemporaryTextStorage(this); } public ITemporaryTextStorage AttachTemporaryTextStorage(string storageName, long offset, long size, Encoding encoding, CancellationToken cancellationToken) { return new TemporaryTextStorage(this, storageName, offset, size, encoding); } public ITemporaryStreamStorage CreateTemporaryStreamStorage(CancellationToken cancellationToken) { return new TemporaryStreamStorage(this); } public ITemporaryStreamStorage AttachTemporaryStreamStorage(string storageName, long offset, long size, CancellationToken cancellationToken) { return new TemporaryStreamStorage(this, storageName, offset, size); } /// <summary> /// Allocate shared storage of a specified size. /// </summary> /// <remarks> /// <para>"Small" requests are fulfilled from oversized memory mapped files which support several individual /// storage units. Larger requests are allocated in their own memory mapped files.</para> /// </remarks> /// <param name="size">The size of the shared storage block to allocate.</param> /// <returns>A <see cref="MemoryMappedInfo"/> describing the allocated block.</returns> private MemoryMappedInfo CreateTemporaryStorage(long size) { if (size >= SingleFileThreshold) { // Larger blocks are allocated separately var mapName = CreateUniqueName(size); var storage = MemoryMappedFile.CreateNew(mapName, size); return new MemoryMappedInfo(new ReferenceCountedDisposable<MemoryMappedFile>(storage), mapName, offset: 0, size: size); } lock (_gate) { // Obtain a reference to the memory mapped file, creating one if necessary. If a reference counted // handle to a memory mapped file is obtained in this section, it must either be disposed before // returning or returned to the caller who will own it through the MemoryMappedInfo. var reference = _weakFileReference.TryAddReference(); if (reference == null || _offset + size > _fileSize) { var mapName = CreateUniqueName(MultiFileBlockSize); var file = MemoryMappedFile.CreateNew(mapName, MultiFileBlockSize); reference = new ReferenceCountedDisposable<MemoryMappedFile>(file); _weakFileReference = new ReferenceCountedDisposable<MemoryMappedFile>.WeakReference(reference); _name = mapName; _fileSize = MultiFileBlockSize; _offset = size; return new MemoryMappedInfo(reference, _name, offset: 0, size: size); } else { // Reserve additional space in the existing storage location _offset += size; return new MemoryMappedInfo(reference, _name, _offset - size, size); } } } public static string CreateUniqueName(long size) { return "Roslyn Temp Storage " + size.ToString() + " " + Guid.NewGuid().ToString("N"); } private class TemporaryTextStorage : ITemporaryTextStorage, ITemporaryStorageWithName { private readonly TemporaryStorageService _service; private Encoding _encoding; private MemoryMappedInfo _memoryMappedInfo; public TemporaryTextStorage(TemporaryStorageService service) { _service = service; } public TemporaryTextStorage(TemporaryStorageService service, string storageName, long offset, long size, Encoding encoding) { _service = service; _encoding = encoding; _memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size); } public string Name => _memoryMappedInfo?.Name; public long Offset => _memoryMappedInfo.Offset; public long Size => _memoryMappedInfo.Size; public void Dispose() { if (_memoryMappedInfo != null) { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo.Dispose(); _memoryMappedInfo = null; } if (_encoding != null) { _encoding = null; } } public SourceText ReadText(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadText, cancellationToken)) { using (var stream = _memoryMappedInfo.CreateReadableStream()) using (var reader = CreateTextReaderFromTemporaryStorage((ISupportDirectMemoryAccess)stream, (int)stream.Length, cancellationToken)) { // we pass in encoding we got from original source text even if it is null. return _service._textFactory.CreateText(reader, _encoding, cancellationToken); } } } public Task<SourceText> ReadTextAsync(CancellationToken cancellationToken) { // There is a reason for implementing it like this: proper async implementation // that reads the underlying memory mapped file stream in an asynchronous fashion // doesn't actually work. Windows doesn't offer // any non-blocking way to read from a memory mapped file; the underlying memcpy // may block as the memory pages back in and that's something you have to live // with. Therefore, any implementation that attempts to use async will still // always be blocking at least one threadpool thread in the memcpy in the case // of a page fault. Therefore, if we're going to be blocking a thread, we should // just block one thread and do the whole thing at once vs. a fake "async" // implementation which will continue to requeue work back to the thread pool. return Task.Factory.StartNew(() => ReadText(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteText(SourceText text, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteText, cancellationToken)) { _encoding = text.Encoding; // the method we use to get text out of SourceText uses Unicode (2bytes per char). var size = Encoding.Unicode.GetMaxByteCount(text.Length); _memoryMappedInfo = _service.CreateTemporaryStorage(size); // Write the source text out as Unicode. We expect that to be cheap. using (var stream = _memoryMappedInfo.CreateWritableStream()) { using (var writer = new StreamWriter(stream, Encoding.Unicode)) { text.Write(writer, cancellationToken); } } } } public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default(CancellationToken)) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => WriteText(text, cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } private unsafe TextReader CreateTextReaderFromTemporaryStorage(ISupportDirectMemoryAccess accessor, int streamLength, CancellationToken cancellationToken) { char* src = (char*)accessor.GetPointer(); // BOM: Unicode, little endian // Skip the BOM when creating the reader Debug.Assert(*src == 0xFEFF); return new DirectMemoryAccessStreamReader(src + 1, streamLength / sizeof(char) - 1); } } private class TemporaryStreamStorage : ITemporaryStreamStorage, ITemporaryStorageWithName { private readonly TemporaryStorageService _service; private MemoryMappedInfo _memoryMappedInfo; public TemporaryStreamStorage(TemporaryStorageService service) { _service = service; } public TemporaryStreamStorage(TemporaryStorageService service, string storageName, long offset, long size) { _service = service; _memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size); } public string Name => _memoryMappedInfo?.Name; public long Offset => _memoryMappedInfo.Offset; public long Size => _memoryMappedInfo.Size; public void Dispose() { if (_memoryMappedInfo != null) { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo.Dispose(); _memoryMappedInfo = null; } } public Stream ReadStream(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadStream, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return _memoryMappedInfo.CreateReadableStream(); } } public Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default(CancellationToken)) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => ReadStream(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteStream(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { // The Wait() here will not actually block, since with useAsync: false, the // entire operation will already be done when WaitStreamMaybeAsync completes. WriteStreamMaybeAsync(stream, useAsync: false, cancellationToken: cancellationToken).GetAwaiter().GetResult(); } public Task WriteStreamAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { return WriteStreamMaybeAsync(stream, useAsync: true, cancellationToken: cancellationToken); } private async Task WriteStreamMaybeAsync(Stream stream, bool useAsync, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(WorkspacesResources.Temporary_storage_cannot_be_written_more_than_once); } if (stream.Length == 0) { throw new ArgumentOutOfRangeException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteStream, cancellationToken)) { var size = stream.Length; _memoryMappedInfo = _service.CreateTemporaryStorage(size); using (var viewStream = _memoryMappedInfo.CreateWritableStream()) { var buffer = SharedPools.ByteArray.Allocate(); try { while (true) { int count; if (useAsync) { count = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); } else { count = stream.Read(buffer, 0, buffer.Length); } if (count == 0) { break; } viewStream.Write(buffer, 0, count); } } finally { SharedPools.ByteArray.Free(buffer); } } } } } } internal unsafe class DirectMemoryAccessStreamReader : TextReaderWithLength { private char* _position; private readonly char* _end; public DirectMemoryAccessStreamReader(char* src, int length) : base(length) { Debug.Assert(src != null); Debug.Assert(length >= 0); _position = src; _end = _position + length; } public override int Peek() { if (_position >= _end) { return -1; } return *_position; } public override int Read() { if (_position >= _end) { return -1; } return *_position++; } public override int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0 || index >= buffer.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0 || (index + count) > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } count = Math.Min(count, (int)(_end - _position)); if (count > 0) { Marshal.Copy((IntPtr)_position, buffer, index, count); _position += count; } return count; } } } }
// 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.Text; using System.Diagnostics; using System.Buffers; namespace System.IO { // This abstract base class represents a writer that can write // primitives to an arbitrary stream. A subclass can override methods to // give unique encodings. // public class BinaryWriter : IDisposable { public static readonly BinaryWriter Null = new BinaryWriter(); protected Stream OutStream; private byte[] _buffer; // temp space for writing primitives to. private Encoding _encoding; private Encoder _encoder; private bool _leaveOpen; // Perf optimization stuff private byte[] _largeByteBuffer; // temp space for writing chars. private int _maxChars; // max # of chars we can put in _largeByteBuffer // Size should be around the max number of chars/string * Encoding's max bytes/char private const int LargeByteBufferSize = 256; // Protected default constructor that sets the output stream // to a null stream (a bit bucket). protected BinaryWriter() { OutStream = Stream.Null; _buffer = new byte[16]; _encoding = EncodingCache.UTF8NoBOM; _encoder = _encoding.GetEncoder(); } public BinaryWriter(Stream output) : this(output, EncodingCache.UTF8NoBOM, false) { } public BinaryWriter(Stream output, Encoding encoding) : this(output, encoding, false) { } public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen) { if (output == null) throw new ArgumentNullException(nameof(output)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (!output.CanWrite) throw new ArgumentException(SR.Argument_StreamNotWritable); OutStream = output; _buffer = new byte[16]; _encoding = encoding; _encoder = _encoding.GetEncoder(); _leaveOpen = leaveOpen; } // Closes this writer and releases any system resources associated with the // writer. Following a call to Close, any operations on the writer // may raise exceptions. public virtual void Close() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_leaveOpen) OutStream.Flush(); else OutStream.Close(); } } public void Dispose() { Dispose(true); } // Returns the stream associated with the writer. It flushes all pending // writes before returning. All subclasses should override Flush to // ensure that all buffered data is sent to the stream. public virtual Stream BaseStream { get { Flush(); return OutStream; } } // Clears all buffers for this writer and causes any buffered data to be // written to the underlying device. public virtual void Flush() { OutStream.Flush(); } public virtual long Seek(int offset, SeekOrigin origin) { return OutStream.Seek(offset, origin); } // Writes a boolean to this stream. A single byte is written to the stream // with the value 0 representing false or the value 1 representing true. // public virtual void Write(bool value) { _buffer[0] = (byte)(value ? 1 : 0); OutStream.Write(_buffer, 0, 1); } // Writes a byte to this stream. The current position of the stream is // advanced by one. // public virtual void Write(byte value) { OutStream.WriteByte(value); } // Writes a signed byte to this stream. The current position of the stream // is advanced by one. // [CLSCompliant(false)] public virtual void Write(sbyte value) { OutStream.WriteByte((byte)value); } // Writes a byte array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the byte array. // public virtual void Write(byte[] buffer) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); OutStream.Write(buffer, 0, buffer.Length); } // Writes a section of a byte array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the byte array. // public virtual void Write(byte[] buffer, int index, int count) { OutStream.Write(buffer, index, count); } // Writes a character to this stream. The current position of the stream is // advanced by two. // Note this method cannot handle surrogates properly in UTF-8. // public unsafe virtual void Write(char ch) { if (char.IsSurrogate(ch)) throw new ArgumentException(SR.Arg_SurrogatesNotAllowedAsSingleChar); Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)"); int numBytes = 0; fixed (byte* pBytes = &_buffer[0]) { numBytes = _encoder.GetBytes(&ch, 1, pBytes, _buffer.Length, flush: true); } OutStream.Write(_buffer, 0, numBytes); } // Writes a character array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the character array. // public virtual void Write(char[] chars) { if (chars == null) throw new ArgumentNullException(nameof(chars)); byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length); OutStream.Write(bytes, 0, bytes.Length); } // Writes a section of a character array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the character array. // public virtual void Write(char[] chars, int index, int count) { byte[] bytes = _encoding.GetBytes(chars, index, count); OutStream.Write(bytes, 0, bytes.Length); } // Writes a double to this stream. The current position of the stream is // advanced by eight. // public unsafe virtual void Write(double value) { ulong TmpValue = *(ulong*)&value; _buffer[0] = (byte)TmpValue; _buffer[1] = (byte)(TmpValue >> 8); _buffer[2] = (byte)(TmpValue >> 16); _buffer[3] = (byte)(TmpValue >> 24); _buffer[4] = (byte)(TmpValue >> 32); _buffer[5] = (byte)(TmpValue >> 40); _buffer[6] = (byte)(TmpValue >> 48); _buffer[7] = (byte)(TmpValue >> 56); OutStream.Write(_buffer, 0, 8); } public virtual void Write(decimal value) { decimal.GetBytes(value, _buffer); OutStream.Write(_buffer, 0, 16); } // Writes a two-byte signed integer to this stream. The current position of // the stream is advanced by two. // public virtual void Write(short value) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); OutStream.Write(_buffer, 0, 2); } // Writes a two-byte unsigned integer to this stream. The current position // of the stream is advanced by two. // [CLSCompliant(false)] public virtual void Write(ushort value) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); OutStream.Write(_buffer, 0, 2); } // Writes a four-byte signed integer to this stream. The current position // of the stream is advanced by four. // public virtual void Write(int value) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); _buffer[2] = (byte)(value >> 16); _buffer[3] = (byte)(value >> 24); OutStream.Write(_buffer, 0, 4); } // Writes a four-byte unsigned integer to this stream. The current position // of the stream is advanced by four. // [CLSCompliant(false)] public virtual void Write(uint value) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); _buffer[2] = (byte)(value >> 16); _buffer[3] = (byte)(value >> 24); OutStream.Write(_buffer, 0, 4); } // Writes an eight-byte signed integer to this stream. The current position // of the stream is advanced by eight. // public virtual void Write(long value) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); _buffer[2] = (byte)(value >> 16); _buffer[3] = (byte)(value >> 24); _buffer[4] = (byte)(value >> 32); _buffer[5] = (byte)(value >> 40); _buffer[6] = (byte)(value >> 48); _buffer[7] = (byte)(value >> 56); OutStream.Write(_buffer, 0, 8); } // Writes an eight-byte unsigned integer to this stream. The current // position of the stream is advanced by eight. // [CLSCompliant(false)] public virtual void Write(ulong value) { _buffer[0] = (byte)value; _buffer[1] = (byte)(value >> 8); _buffer[2] = (byte)(value >> 16); _buffer[3] = (byte)(value >> 24); _buffer[4] = (byte)(value >> 32); _buffer[5] = (byte)(value >> 40); _buffer[6] = (byte)(value >> 48); _buffer[7] = (byte)(value >> 56); OutStream.Write(_buffer, 0, 8); } // Writes a float to this stream. The current position of the stream is // advanced by four. // public unsafe virtual void Write(float value) { uint TmpValue = *(uint*)&value; _buffer[0] = (byte)TmpValue; _buffer[1] = (byte)(TmpValue >> 8); _buffer[2] = (byte)(TmpValue >> 16); _buffer[3] = (byte)(TmpValue >> 24); OutStream.Write(_buffer, 0, 4); } // Writes a length-prefixed string to this stream in the BinaryWriter's // current Encoding. This method first writes the length of the string as // a four-byte unsigned integer, and then writes that many characters // to the stream. // public unsafe virtual void Write(string value) { if (value == null) throw new ArgumentNullException(nameof(value)); int len = _encoding.GetByteCount(value); Write7BitEncodedInt(len); if (_largeByteBuffer == null) { _largeByteBuffer = new byte[LargeByteBufferSize]; _maxChars = _largeByteBuffer.Length / _encoding.GetMaxByteCount(1); } if (len <= _largeByteBuffer.Length) { //Debug.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name); _encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0); OutStream.Write(_largeByteBuffer, 0, len); } else { // Aggressively try to not allocate memory in this loop for // runtime performance reasons. Use an Encoder to write out // the string correctly (handling surrogates crossing buffer // boundaries properly). int charStart = 0; int numLeft = value.Length; #if DEBUG int totalBytes = 0; #endif while (numLeft > 0) { // Figure out how many chars to process this round. int charCount = (numLeft > _maxChars) ? _maxChars : numLeft; int byteLen; checked { if (charStart < 0 || charCount < 0 || charStart > value.Length - charCount) { throw new ArgumentOutOfRangeException(nameof(charCount)); } fixed (char* pChars = value) { fixed (byte* pBytes = &_largeByteBuffer[0]) { byteLen = _encoder.GetBytes(pChars + charStart, charCount, pBytes, _largeByteBuffer.Length, charCount == numLeft); } } } #if DEBUG totalBytes += byteLen; Debug.Assert(totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!"); #endif OutStream.Write(_largeByteBuffer, 0, byteLen); charStart += charCount; numLeft -= charCount; } #if DEBUG Debug.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!"); #endif } } public virtual void Write(ReadOnlySpan<byte> buffer) { if (GetType() == typeof(BinaryWriter)) { OutStream.Write(buffer); } else { byte[] array = ArrayPool<byte>.Shared.Rent(buffer.Length); try { buffer.CopyTo(array); Write(array, 0, buffer.Length); } finally { ArrayPool<byte>.Shared.Return(array); } } } public virtual void Write(ReadOnlySpan<char> chars) { byte[] bytes = ArrayPool<byte>.Shared.Rent(_encoding.GetMaxByteCount(chars.Length)); try { int bytesWritten = _encoding.GetBytes(chars, bytes); Write(bytes, 0, bytesWritten); } finally { ArrayPool<byte>.Shared.Return(bytes); } } protected void Write7BitEncodedInt(int value) { // Write out an int 7 bits at a time. The high bit of the byte, // when on, tells reader to continue reading more bytes. uint v = (uint)value; // support negative numbers while (v >= 0x80) { Write((byte)(v | 0x80)); v >>= 7; } Write((byte)v); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using AutoMapper.Configuration; namespace AutoMapper { /// <summary> /// Contains cached reflection information for easy retrieval /// </summary> [DebuggerDisplay("{Type}")] public class TypeDetails { public TypeDetails(Type type, ProfileMap config) { Type = type; var membersToMap = MembersToMap(config.ShouldMapProperty, config.ShouldMapField); var publicReadableMembers = GetAllPublicReadableMembers(membersToMap); var publicWritableMembers = GetAllPublicWritableMembers(membersToMap); PublicReadAccessors = BuildPublicReadAccessors(publicReadableMembers); PublicWriteAccessors = BuildPublicAccessors(publicWritableMembers); PublicNoArgMethods = BuildPublicNoArgMethods(config.ShouldMapMethod); Constructors = GetAllConstructors(config.ShouldUseConstructor); PublicNoArgExtensionMethods = BuildPublicNoArgExtensionMethods(config.SourceExtensionMethods.Where(config.ShouldMapMethod)); AllMembers = PublicReadAccessors.Concat(PublicNoArgMethods).Concat(PublicNoArgExtensionMethods).ToList(); DestinationMemberNames = AllMembers.Select(mi => new DestinationMemberName { Member = mi, Possibles = PossibleNames(mi.Name, config.Prefixes, config.Postfixes).ToArray() }); } private IEnumerable<string> PossibleNames(string memberName, IEnumerable<string> prefixes, IEnumerable<string> postfixes) { yield return memberName; if (!postfixes.Any()) { foreach (var withoutPrefix in prefixes.Where(prefix => memberName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).Select(prefix => memberName.Substring(prefix.Length))) { yield return withoutPrefix; } yield break; } foreach (var withoutPrefix in prefixes.Where(prefix => memberName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).Select(prefix => memberName.Substring(prefix.Length))) { yield return withoutPrefix; foreach (var s in PostFixes(postfixes, withoutPrefix)) yield return s; } foreach (var s in PostFixes(postfixes, memberName)) yield return s; } private static IEnumerable<string> PostFixes(IEnumerable<string> postfixes, string name) { return postfixes.Where(postfix => name.EndsWith(postfix, StringComparison.OrdinalIgnoreCase)) .Select(postfix => name.Remove(name.Length - postfix.Length)); } private static Func<MemberInfo, bool> MembersToMap( Func<PropertyInfo, bool> shouldMapProperty, Func<FieldInfo, bool> shouldMapField) { return m => { switch (m) { case PropertyInfo property: return !property.IsStatic() && shouldMapProperty(property); case FieldInfo field: return !field.IsStatic && shouldMapField(field); default: throw new ArgumentException("Should be a field or a property."); } }; } public struct DestinationMemberName { public MemberInfo Member { get; set; } public string[] Possibles { get; set; } } public Type Type { get; } public IEnumerable<ConstructorInfo> Constructors { get; } public IEnumerable<MemberInfo> PublicReadAccessors { get; } public IEnumerable<MemberInfo> PublicWriteAccessors { get; } public IEnumerable<MethodInfo> PublicNoArgMethods { get; } public IEnumerable<MethodInfo> PublicNoArgExtensionMethods { get; } public IEnumerable<MemberInfo> AllMembers { get; } public IEnumerable<DestinationMemberName> DestinationMemberNames { get; set; } private IEnumerable<MethodInfo> BuildPublicNoArgExtensionMethods(IEnumerable<MethodInfo> sourceExtensionMethodSearch) { var explicitExtensionMethods = sourceExtensionMethodSearch.Where(method => method.GetParameters()[0].ParameterType == Type); var genericInterfaces = Type.GetTypeInfo().ImplementedInterfaces.Where(t => t.IsGenericType()); if (Type.IsInterface() && Type.IsGenericType()) { genericInterfaces = genericInterfaces.Union(new[] { Type }); } return explicitExtensionMethods.Union ( from genericInterface in genericInterfaces let genericInterfaceArguments = genericInterface.GetTypeInfo().GenericTypeArguments let matchedMethods = ( from extensionMethod in sourceExtensionMethodSearch where !extensionMethod.IsGenericMethodDefinition select extensionMethod ).Concat( from extensionMethod in sourceExtensionMethodSearch where extensionMethod.IsGenericMethodDefinition && extensionMethod.GetGenericArguments().Length == genericInterfaceArguments.Length select extensionMethod.MakeGenericMethod(genericInterfaceArguments) ) from methodMatch in matchedMethods where methodMatch.GetParameters()[0].ParameterType.GetTypeInfo().IsAssignableFrom(genericInterface.GetTypeInfo()) select methodMatch ).ToArray(); } private static MemberInfo[] BuildPublicReadAccessors(IEnumerable<MemberInfo> allMembers) { // Multiple types may define the same property (e.g. the class and multiple interfaces) - filter this to one of those properties var filteredMembers = allMembers .OfType<PropertyInfo>() .GroupBy(x => x.Name) // group properties of the same name together .Select(x => x.First()) .Concat(allMembers.Where(x => x is FieldInfo)); // add FieldInfo objects back return filteredMembers.ToArray(); } private static MemberInfo[] BuildPublicAccessors(IEnumerable<MemberInfo> allMembers) { // Multiple types may define the same property (e.g. the class and multiple interfaces) - filter this to one of those properties var filteredMembers = allMembers .OfType<PropertyInfo>() .GroupBy(x => x.Name) // group properties of the same name together .Select(x => x.Any(y => y.CanWrite && y.CanRead) ? // favor the first property that can both read & write - otherwise pick the first one x.First(y => y.CanWrite && y.CanRead) : x.First()) .Where(pi => pi.CanWrite || pi.PropertyType.IsListOrDictionaryType()) //.OfType<MemberInfo>() // cast back to MemberInfo so we can add back FieldInfo objects .Concat(allMembers.Where(x => x is FieldInfo)); // add FieldInfo objects back return filteredMembers.ToArray(); } private IEnumerable<MemberInfo> GetAllPublicReadableMembers(Func<MemberInfo, bool> membersToMap) => GetAllPublicMembers(PropertyReadable, FieldReadable, membersToMap); private IEnumerable<MemberInfo> GetAllPublicWritableMembers(Func<MemberInfo, bool> membersToMap) => GetAllPublicMembers(PropertyWritable, FieldWritable, membersToMap); private IEnumerable<ConstructorInfo> GetAllConstructors(Func<ConstructorInfo, bool> shouldUseConstructor) { return Type.GetDeclaredConstructors().Where(shouldUseConstructor).ToArray(); } private static bool PropertyReadable(PropertyInfo propertyInfo) => propertyInfo.CanRead; private static bool FieldReadable(FieldInfo fieldInfo) => true; private static bool PropertyWritable(PropertyInfo propertyInfo) => propertyInfo.CanWrite || propertyInfo.PropertyType.IsNonStringEnumerable(); private static bool FieldWritable(FieldInfo fieldInfo) => !fieldInfo.IsInitOnly; private IEnumerable<MemberInfo> GetAllPublicMembers( Func<PropertyInfo, bool> propertyAvailableFor, Func<FieldInfo, bool> fieldAvailableFor, Func<MemberInfo, bool> memberAvailableFor) { var typesToScan = new List<Type>(); for (var t = Type; t != null; t = t.BaseType()) typesToScan.Add(t); if (Type.IsInterface()) typesToScan.AddRange(Type.GetTypeInfo().ImplementedInterfaces); // Scan all types for public properties and fields return typesToScan .Where(x => x != null) // filter out null types (e.g. type.BaseType == null) .SelectMany(x => x.GetDeclaredMembers() .Where(mi => mi.DeclaringType != null && mi.DeclaringType == x) .Where( m => m is FieldInfo && fieldAvailableFor((FieldInfo)m) || m is PropertyInfo && propertyAvailableFor((PropertyInfo)m) && !((PropertyInfo)m).GetIndexParameters().Any()) .Where(memberAvailableFor) ); } private MethodInfo[] BuildPublicNoArgMethods(Func<MethodInfo, bool> shouldMapMethod) { return Type.GetAllMethods() .Where(shouldMapMethod) .Where(mi => mi.IsPublic && !mi.IsStatic && mi.DeclaringType != typeof(object)) .Where(m => (m.ReturnType != typeof(void)) && (m.GetParameters().Length == 0)) .ToArray(); } } }
using System; using System.Collections.Generic; using UnityEngine; using DarkMultiPlayerCommon; namespace DarkMultiPlayer { public class PlayerStatusWindow { public bool display = false; public bool disconnectEventHandled = true; public bool colorEventHandled = true; private bool isWindowLocked = false; //private parts private static PlayerStatusWindow singleton; private bool initialized; private Vector2 scrollPosition; public bool minmized; private bool safeMinimized; //GUI Layout private bool calculatedMinSize; private Rect windowRect; private Rect minWindowRect; private Rect moveRect; private GUILayoutOption[] layoutOptions; private GUILayoutOption[] minLayoutOptions; //Styles private GUIStyle windowStyle; private GUIStyle subspaceStyle; private GUIStyle buttonStyle; private GUIStyle highlightStyle; private GUIStyle scrollStyle; private Dictionary<string, GUIStyle> playerNameStyle; private GUIStyle vesselNameStyle; private GUIStyle stateTextStyle; //Player status dictionaries private SubspaceDisplayEntry[] subspaceDisplay; private double lastStatusUpdate; //const private const float WINDOW_HEIGHT = 400; private const float WINDOW_WIDTH = 300; private const float UPDATE_STATUS_INTERVAL = .2f; public static PlayerStatusWindow fetch { get { return singleton; } } private void InitGUI() { //Setup GUI stuff windowRect = new Rect(Screen.width * 0.9f - WINDOW_WIDTH, Screen.height / 2f - WINDOW_HEIGHT / 2f, WINDOW_WIDTH, WINDOW_HEIGHT); minWindowRect = new Rect(float.NegativeInfinity, float.NegativeInfinity, 0, 0); moveRect = new Rect(0, 0, 10000, 20); windowStyle = new GUIStyle(GUI.skin.window); buttonStyle = new GUIStyle(GUI.skin.button); highlightStyle = new GUIStyle(GUI.skin.button); highlightStyle.normal.textColor = Color.red; highlightStyle.active.textColor = Color.red; highlightStyle.hover.textColor = Color.red; scrollStyle = new GUIStyle(GUI.skin.scrollView); subspaceStyle = new GUIStyle(); subspaceStyle.normal.background = new Texture2D(1, 1); subspaceStyle.normal.background.SetPixel(0, 0, Color.black); subspaceStyle.normal.background.Apply(); layoutOptions = new GUILayoutOption[4]; layoutOptions[0] = GUILayout.MinWidth(WINDOW_WIDTH); layoutOptions[1] = GUILayout.MaxWidth(WINDOW_WIDTH); layoutOptions[2] = GUILayout.MinHeight(WINDOW_HEIGHT); layoutOptions[3] = GUILayout.MaxHeight(WINDOW_HEIGHT); minLayoutOptions = new GUILayoutOption[4]; minLayoutOptions[0] = GUILayout.MinWidth(0); minLayoutOptions[1] = GUILayout.MinHeight(0); minLayoutOptions[2] = GUILayout.ExpandHeight(true); minLayoutOptions[3] = GUILayout.ExpandWidth(true); //Adapted from KMP. playerNameStyle = new Dictionary<string, GUIStyle>(); vesselNameStyle = new GUIStyle(GUI.skin.label); vesselNameStyle.normal.textColor = Color.white; vesselNameStyle.hover.textColor = vesselNameStyle.normal.textColor; vesselNameStyle.active.textColor = vesselNameStyle.normal.textColor; vesselNameStyle.fontStyle = FontStyle.Normal; vesselNameStyle.fontSize = 12; vesselNameStyle.stretchWidth = true; stateTextStyle = new GUIStyle(GUI.skin.label); stateTextStyle.normal.textColor = new Color(0.75f, 0.75f, 0.75f); stateTextStyle.hover.textColor = stateTextStyle.normal.textColor; stateTextStyle.active.textColor = stateTextStyle.normal.textColor; stateTextStyle.fontStyle = FontStyle.Normal; stateTextStyle.fontSize = 12; stateTextStyle.stretchWidth = true; subspaceDisplay = new SubspaceDisplayEntry[0]; } private void Update() { display = Client.fetch.gameRunning; if (display) { safeMinimized = minmized; if (!calculatedMinSize && minWindowRect.width != 0 && minWindowRect.height != 0) { calculatedMinSize = true; } if ((UnityEngine.Time.realtimeSinceStartup - lastStatusUpdate) > UPDATE_STATUS_INTERVAL) { lastStatusUpdate = UnityEngine.Time.realtimeSinceStartup; subspaceDisplay = WarpWorker.fetch.GetSubspaceDisplayEntries(); } } } private void Draw() { if (!colorEventHandled) { playerNameStyle = new Dictionary<string, GUIStyle>(); colorEventHandled = true; } if (!initialized) { initialized = true; InitGUI(); } if (display) { //Calculate the minimum size of the minimize window by drawing it off the screen if (!calculatedMinSize) { minWindowRect = GUILayout.Window(6701 + Client.WINDOW_OFFSET, minWindowRect, DrawMaximize, "DMP", windowStyle, minLayoutOptions); } if (!safeMinimized) { windowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6703 + Client.WINDOW_OFFSET, windowRect, DrawContent, "DarkMultiPlayer - Status", windowStyle, layoutOptions)); } else { minWindowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6703 + Client.WINDOW_OFFSET, minWindowRect, DrawMaximize, "DMP", windowStyle, minLayoutOptions)); } } CheckWindowLock(); } private void DrawContent(int windowID) { GUILayout.BeginVertical(); GUI.DragWindow(moveRect); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUIStyle chatButtonStyle = buttonStyle; if (ChatWorker.fetch.chatButtonHighlighted) { chatButtonStyle = highlightStyle; } ChatWorker.fetch.display = GUILayout.Toggle(ChatWorker.fetch.display, "Chat", chatButtonStyle); CraftLibraryWorker.fetch.display = GUILayout.Toggle(CraftLibraryWorker.fetch.display, "Craft", buttonStyle); DebugWindow.fetch.display = GUILayout.Toggle(DebugWindow.fetch.display, "Debug", buttonStyle); GUIStyle screenshotButtonStyle = buttonStyle; if (ScreenshotWorker.fetch.screenshotButtonHighlighted) { screenshotButtonStyle = highlightStyle; } ScreenshotWorker.fetch.display = GUILayout.Toggle(ScreenshotWorker.fetch.display, "Screenshot", screenshotButtonStyle); if (GUILayout.Button("-", buttonStyle)) { minmized = true; minWindowRect.x = windowRect.xMax - minWindowRect.width; minWindowRect.y = windowRect.y; } GUILayout.EndHorizontal(); scrollPosition = GUILayout.BeginScrollView(scrollPosition, scrollStyle); //Draw subspaces double ourTime = TimeSyncer.fetch.locked ? TimeSyncer.fetch.GetUniverseTime() : Planetarium.GetUniversalTime(); long serverClock = TimeSyncer.fetch.GetServerClock(); foreach (SubspaceDisplayEntry currentEntry in subspaceDisplay) { double currentTime = 0; double diffTime = 0; string diffState = "Unknown"; if (!currentEntry.isUs) { if (!currentEntry.isWarping) { //Subspace entry if (currentEntry.subspaceEntry != null) { long serverClockDiff = serverClock - currentEntry.subspaceEntry.serverClock; double secondsDiff = serverClockDiff / 10000000d; currentTime = currentEntry.subspaceEntry.planetTime + (currentEntry.subspaceEntry.subspaceSpeed * secondsDiff); diffTime = currentTime - ourTime; diffState = (diffTime > 0) ? SecondsToVeryShortString((int)diffTime) + " in the future" : SecondsToVeryShortString(-(int)diffTime) + " in the past"; } } else { //Warp entry if (currentEntry.warpingEntry != null) { float[] warpRates = TimeWarp.fetch.warpRates; if (currentEntry.warpingEntry.isPhysWarp) { warpRates = TimeWarp.fetch.physicsWarpRates; } long serverClockDiff = serverClock - currentEntry.warpingEntry.serverClock; double secondsDiff = serverClockDiff / 10000000d; currentTime = currentEntry.warpingEntry.planetTime + (warpRates[currentEntry.warpingEntry.rateIndex] * secondsDiff); diffTime = currentTime - ourTime; diffState = (diffTime > 0) ? SecondsToVeryShortString((int)diffTime) + " in the future" : SecondsToVeryShortString(-(int)diffTime) + " in the past"; } } } else { currentTime = ourTime; diffState = "NOW"; } //Draw the subspace black bar. GUILayout.BeginHorizontal(subspaceStyle); GUILayout.Label("T+ " + SecondsToShortString((int)currentTime) + " - " + diffState); GUILayout.FlexibleSpace(); //Draw the sync button if needed if ((WarpWorker.fetch.warpMode == WarpMode.SUBSPACE) && !currentEntry.isUs && !currentEntry.isWarping && (currentEntry.subspaceEntry != null) && (diffTime > 0)) { if (GUILayout.Button("Sync", buttonStyle)) { TimeSyncer.fetch.LockSubspace(currentEntry.subspaceID); } } GUILayout.EndHorizontal(); foreach (string currentPlayer in currentEntry.players) { if (currentPlayer == Settings.fetch.playerName) { DrawPlayerEntry(PlayerStatusWorker.fetch.myPlayerStatus); } else { DrawPlayerEntry(PlayerStatusWorker.fetch.GetPlayerStatus(currentPlayer)); } } } GUILayout.EndScrollView(); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); if (GUILayout.Button("Disconnect", buttonStyle)) { disconnectEventHandled = false; } OptionsWindow.fetch.display = GUILayout.Toggle(OptionsWindow.fetch.display, "Options", buttonStyle); GUILayout.EndHorizontal(); GUILayout.EndVertical(); } private void CheckWindowLock() { if (!Client.fetch.gameRunning) { RemoveWindowLock(); return; } if (HighLogic.LoadedSceneIsFlight) { RemoveWindowLock(); return; } if (display) { Vector2 mousePos = Input.mousePosition; mousePos.y = Screen.height - mousePos.y; bool shouldLock = (minmized ? minWindowRect.Contains(mousePos) : windowRect.Contains(mousePos)); if (shouldLock && !isWindowLocked) { InputLockManager.SetControlLock(ControlTypes.ALLBUTCAMERAS, "DMP_PlayerStatusLock"); isWindowLocked = true; } if (!shouldLock && isWindowLocked) { RemoveWindowLock(); } } if (!display && isWindowLocked) { RemoveWindowLock(); } } private void RemoveWindowLock() { if (isWindowLocked) { isWindowLocked = false; InputLockManager.RemoveControlLock( "DMP_PlayerStatusLock"); } } private string SecondsToLongString(int time) { //Every month is feburary ok? int years = time / (60 * 60 * 24 * 7 * 4 * 12); time -= years * (60 * 60 * 24 * 7 * 4 * 12); int months = time / (60 * 60 * 24 * 7 * 4); time -= months * (60 * 60 * 24 * 7 * 4); int weeks = time / (60 * 60 * 24 * 7); time -= weeks * (60 * 60 * 24 * 7); int days = time / (60 * 60 * 24); time -= days * (60 * 60 * 24); int hours = time / (60 * 60); time -= hours * (60 * 60); int minutes = time / 60; time -= minutes * 60; int seconds = time; string returnString = ""; if (years > 0) { if (years == 1) { returnString += "1 year"; } else { returnString += years + " years"; } } if (returnString != "") { returnString += ", "; } if (months > 0) { if (months == 1) { returnString += "1 month"; } else { returnString += months + " month"; } } if (returnString != "") { returnString += ", "; } if (weeks > 0) { if (weeks == 1) { returnString += "1 week"; } else { returnString += weeks + " weeks"; } } if (returnString != "") { returnString += ", "; } if (days > 0) { if (days == 1) { returnString += "1 day"; } else { returnString += days + " days"; } } if (returnString != "") { returnString += ", "; } if (hours > 0) { if (hours == 1) { returnString += "1 hour"; } else { returnString += hours + " hours"; } } if (returnString != "") { returnString += ", "; } if (minutes > 0) { if (minutes == 1) { returnString += "1 minute"; } else { returnString += minutes + " minutes"; } } if (returnString != "") { returnString += ", "; } if (seconds == 1) { returnString += "1 second"; } else { returnString += seconds + " seconds"; } return returnString; } private string SecondsToShortString(int time) { int years = time / (60 * 60 * 24 * 7 * 4 * 12); time -= years * (60 * 60 * 24 * 7 * 4 * 12); int months = time / (60 * 60 * 24 * 7 * 4); time -= months * (60 * 60 * 24 * 7 * 4); int weeks = time / (60 * 60 * 24 * 7); time -= weeks * (60 * 60 * 24 * 7); int days = time / (60 * 60 * 24); time -= days * (60 * 60 * 24); int hours = time / (60 * 60); time -= hours * (60 * 60); int minutes = time / 60; time -= minutes * 60; int seconds = time; string returnString = ""; if (years > 0) { if (years == 1) { returnString += "1y, "; } else { returnString += years + "y, "; } } if (months > 0) { if (months == 1) { returnString += "1m, "; } else { returnString += months + "m, "; } } if (weeks > 0) { if (weeks == 1) { returnString += "1w, "; } else { returnString += weeks + "w, "; } } if (days > 0) { if (days == 1) { returnString += "1d, "; } else { returnString += days + "d, "; } } returnString += hours.ToString("00") + ":" + minutes.ToString("00") + ":" + seconds.ToString("00"); return returnString; } private string SecondsToVeryShortString(int time) { int years = time / (60 * 60 * 24 * 7 * 4 * 12); time -= years * (60 * 60 * 24 * 7 * 4 * 12); int months = time / (60 * 60 * 24 * 7 * 4); time -= months * (60 * 60 * 24 * 7 * 4); int weeks = time / (60 * 60 * 24 * 7); time -= weeks * (60 * 60 * 24 * 7); int days = time / (60 * 60 * 24); time -= days * (60 * 60 * 24); int hours = time / (60 * 60); time -= hours * (60 * 60); int minutes = time / 60; time -= minutes * 60; int seconds = time; if (years > 0) { if (years == 1) { return "1 year"; } else { return years + " years"; } } if (months > 0) { if (months == 1) { return "1 month"; } else { return months + " months"; } } if (weeks > 0) { if (weeks == 1) { return "1 week"; } else { return weeks + " weeks"; } } if (days > 0) { if (days == 1) { return "1 day"; } else { return days + " days"; } } if (hours > 0) { if (hours == 1) { return "1 hour"; } else { return hours + " hours"; } } if (minutes > 0) { if (minutes == 1) { return "1 minute"; } else { return minutes + " minutes"; } } if (seconds == 1) { return "1 second"; } else { return seconds + " seconds"; } } private void DrawMaximize(int windowID) { GUI.DragWindow(moveRect); GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); GUIStyle chatButtonStyle = buttonStyle; if (ChatWorker.fetch.chatButtonHighlighted) { chatButtonStyle = highlightStyle; } ChatWorker.fetch.display = GUILayout.Toggle(ChatWorker.fetch.display, "C", chatButtonStyle); DebugWindow.fetch.display = GUILayout.Toggle(DebugWindow.fetch.display, "D", buttonStyle); GUIStyle screenshotButtonStyle = buttonStyle; if (ScreenshotWorker.fetch.screenshotButtonHighlighted) { screenshotButtonStyle = highlightStyle; } ScreenshotWorker.fetch.display = GUILayout.Toggle(ScreenshotWorker.fetch.display, "S", screenshotButtonStyle); OptionsWindow.fetch.display = GUILayout.Toggle(OptionsWindow.fetch.display, "O", buttonStyle); if (GUILayout.Button("+", buttonStyle)) { windowRect.xMax = minWindowRect.xMax; windowRect.yMin = minWindowRect.yMin; windowRect.xMin = minWindowRect.xMax - WINDOW_WIDTH; windowRect.yMax = minWindowRect.yMin + WINDOW_HEIGHT; minmized = false; } GUILayout.EndHorizontal(); GUILayout.EndVertical(); } private void DrawPlayerEntry(PlayerStatus playerStatus) { if (playerStatus == null) { //Just connected or disconnected. return; } GUILayout.BeginHorizontal(); if (!playerNameStyle.ContainsKey(playerStatus.playerName)) { playerNameStyle[playerStatus.playerName] = new GUIStyle(GUI.skin.label); playerNameStyle[playerStatus.playerName].normal.textColor = PlayerColorWorker.fetch.GetPlayerColor(playerStatus.playerName); playerNameStyle[playerStatus.playerName].hover.textColor = PlayerColorWorker.fetch.GetPlayerColor(playerStatus.playerName); playerNameStyle[playerStatus.playerName].active.textColor = PlayerColorWorker.fetch.GetPlayerColor(playerStatus.playerName); playerNameStyle[playerStatus.playerName].fontStyle = FontStyle.Bold; playerNameStyle[playerStatus.playerName].stretchWidth = true; playerNameStyle[playerStatus.playerName].wordWrap = false; } GUILayout.Label(playerStatus.playerName, playerNameStyle[playerStatus.playerName]); GUILayout.FlexibleSpace(); GUILayout.Label(playerStatus.statusText, stateTextStyle); GUILayout.EndHorizontal(); if (playerStatus.vesselText != "") { GUILayout.Label("Pilot: " + playerStatus.vesselText, vesselNameStyle); } } public static void Reset() { lock (Client.eventLock) { if (singleton != null) { singleton.display = false; singleton.RemoveWindowLock(); Client.updateEvent.Remove(singleton.Update); Client.drawEvent.Remove(singleton.Draw); } singleton = new PlayerStatusWindow(); Client.updateEvent.Add(singleton.Update); Client.drawEvent.Add(singleton.Draw); } } } }
namespace java.lang.reflect { [global::MonoJavaBridge.JavaClass()] public sealed partial class Field : java.lang.reflect.AccessibleObject, Member { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Field() { InitJNI(); } internal Field(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _get13454; public global::java.lang.Object get(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Field._get13454, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._get13454, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _equals13455; public sealed override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.reflect.Field._equals13455, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._equals13455, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString13456; public sealed override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Field._toString13456)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._toString13456)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _hashCode13457; public sealed override int hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.reflect.Field._hashCode13457); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._hashCode13457); } internal static global::MonoJavaBridge.MethodId _getModifiers13458; public int getModifiers() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.reflect.Field._getModifiers13458); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getModifiers13458); } internal static global::MonoJavaBridge.MethodId _getBoolean13459; public bool getBoolean(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.reflect.Field._getBoolean13459, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getBoolean13459, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getByte13460; public byte getByte(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallByteMethod(this.JvmHandle, global::java.lang.reflect.Field._getByte13460, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualByteMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getByte13460, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getShort13461; public short getShort(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallShortMethod(this.JvmHandle, global::java.lang.reflect.Field._getShort13461, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualShortMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getShort13461, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getChar13462; public char getChar(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallCharMethod(this.JvmHandle, global::java.lang.reflect.Field._getChar13462, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualCharMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getChar13462, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getInt13463; public int getInt(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.reflect.Field._getInt13463, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getInt13463, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getLong13464; public long getLong(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.lang.reflect.Field._getLong13464, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getLong13464, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getFloat13465; public float getFloat(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::java.lang.reflect.Field._getFloat13465, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getFloat13465, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDouble13466; public double getDouble(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallDoubleMethod(this.JvmHandle, global::java.lang.reflect.Field._getDouble13466, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getDouble13466, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getName13467; public global::java.lang.String getName() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Field._getName13467)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getName13467)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _isSynthetic13468; public bool isSynthetic() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.reflect.Field._isSynthetic13468); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._isSynthetic13468); } internal static global::MonoJavaBridge.MethodId _getDeclaringClass13469; public global::java.lang.Class getDeclaringClass() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Field._getDeclaringClass13469)) as java.lang.Class; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getDeclaringClass13469)) as java.lang.Class; } internal static global::MonoJavaBridge.MethodId _getAnnotation13470; public sealed override global::java.lang.annotation.Annotation getAnnotation(java.lang.Class arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.annotation.Annotation>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Field._getAnnotation13470, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.annotation.Annotation; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.annotation.Annotation>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getAnnotation13470, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.annotation.Annotation; } internal static global::MonoJavaBridge.MethodId _getDeclaredAnnotations13471; public sealed override global::java.lang.annotation.Annotation[] getDeclaredAnnotations() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.annotation.Annotation>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Field._getDeclaredAnnotations13471)) as java.lang.annotation.Annotation[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.annotation.Annotation>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getDeclaredAnnotations13471)) as java.lang.annotation.Annotation[]; } internal static global::MonoJavaBridge.MethodId _isEnumConstant13472; public bool isEnumConstant() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.reflect.Field._isEnumConstant13472); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._isEnumConstant13472); } internal static global::MonoJavaBridge.MethodId _getType13473; public global::java.lang.Class getType() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Field._getType13473)) as java.lang.Class; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getType13473)) as java.lang.Class; } internal static global::MonoJavaBridge.MethodId _getGenericType13474; public global::java.lang.reflect.Type getGenericType() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.reflect.Type>(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Field._getGenericType13474)) as java.lang.reflect.Type; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.reflect.Type>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._getGenericType13474)) as java.lang.reflect.Type; } internal static global::MonoJavaBridge.MethodId _toGenericString13475; public global::java.lang.String toGenericString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.reflect.Field._toGenericString13475)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._toGenericString13475)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _set13476; public void set(java.lang.Object arg0, java.lang.Object arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.reflect.Field._set13476, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._set13476, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setBoolean13477; public void setBoolean(java.lang.Object arg0, bool arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.reflect.Field._setBoolean13477, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._setBoolean13477, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setByte13478; public void setByte(java.lang.Object arg0, byte arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.reflect.Field._setByte13478, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._setByte13478, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setChar13479; public void setChar(java.lang.Object arg0, char arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.reflect.Field._setChar13479, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._setChar13479, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setShort13480; public void setShort(java.lang.Object arg0, short arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.reflect.Field._setShort13480, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._setShort13480, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setInt13481; public void setInt(java.lang.Object arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.reflect.Field._setInt13481, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._setInt13481, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setLong13482; public void setLong(java.lang.Object arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.reflect.Field._setLong13482, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._setLong13482, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setFloat13483; public void setFloat(java.lang.Object arg0, float arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.reflect.Field._setFloat13483, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._setFloat13483, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setDouble13484; public void setDouble(java.lang.Object arg0, double arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.lang.reflect.Field._setDouble13484, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.lang.reflect.Field.staticClass, global::java.lang.reflect.Field._setDouble13484, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.lang.reflect.Field.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/reflect/Field")); global::java.lang.reflect.Field._get13454 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "get", "(Ljava/lang/Object;)Ljava/lang/Object;"); global::java.lang.reflect.Field._equals13455 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::java.lang.reflect.Field._toString13456 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "toString", "()Ljava/lang/String;"); global::java.lang.reflect.Field._hashCode13457 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "hashCode", "()I"); global::java.lang.reflect.Field._getModifiers13458 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getModifiers", "()I"); global::java.lang.reflect.Field._getBoolean13459 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getBoolean", "(Ljava/lang/Object;)Z"); global::java.lang.reflect.Field._getByte13460 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getByte", "(Ljava/lang/Object;)B"); global::java.lang.reflect.Field._getShort13461 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getShort", "(Ljava/lang/Object;)S"); global::java.lang.reflect.Field._getChar13462 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getChar", "(Ljava/lang/Object;)C"); global::java.lang.reflect.Field._getInt13463 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getInt", "(Ljava/lang/Object;)I"); global::java.lang.reflect.Field._getLong13464 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getLong", "(Ljava/lang/Object;)J"); global::java.lang.reflect.Field._getFloat13465 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getFloat", "(Ljava/lang/Object;)F"); global::java.lang.reflect.Field._getDouble13466 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getDouble", "(Ljava/lang/Object;)D"); global::java.lang.reflect.Field._getName13467 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getName", "()Ljava/lang/String;"); global::java.lang.reflect.Field._isSynthetic13468 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "isSynthetic", "()Z"); global::java.lang.reflect.Field._getDeclaringClass13469 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getDeclaringClass", "()Ljava/lang/Class;"); global::java.lang.reflect.Field._getAnnotation13470 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getAnnotation", "(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;"); global::java.lang.reflect.Field._getDeclaredAnnotations13471 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getDeclaredAnnotations", "()[Ljava/lang/annotation/Annotation;"); global::java.lang.reflect.Field._isEnumConstant13472 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "isEnumConstant", "()Z"); global::java.lang.reflect.Field._getType13473 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getType", "()Ljava/lang/Class;"); global::java.lang.reflect.Field._getGenericType13474 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "getGenericType", "()Ljava/lang/reflect/Type;"); global::java.lang.reflect.Field._toGenericString13475 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "toGenericString", "()Ljava/lang/String;"); global::java.lang.reflect.Field._set13476 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "set", "(Ljava/lang/Object;Ljava/lang/Object;)V"); global::java.lang.reflect.Field._setBoolean13477 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "setBoolean", "(Ljava/lang/Object;Z)V"); global::java.lang.reflect.Field._setByte13478 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "setByte", "(Ljava/lang/Object;B)V"); global::java.lang.reflect.Field._setChar13479 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "setChar", "(Ljava/lang/Object;C)V"); global::java.lang.reflect.Field._setShort13480 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "setShort", "(Ljava/lang/Object;S)V"); global::java.lang.reflect.Field._setInt13481 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "setInt", "(Ljava/lang/Object;I)V"); global::java.lang.reflect.Field._setLong13482 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "setLong", "(Ljava/lang/Object;J)V"); global::java.lang.reflect.Field._setFloat13483 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "setFloat", "(Ljava/lang/Object;F)V"); global::java.lang.reflect.Field._setDouble13484 = @__env.GetMethodIDNoThrow(global::java.lang.reflect.Field.staticClass, "setDouble", "(Ljava/lang/Object;D)V"); } } }
using System; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.DefaultPort; using Microsoft.VisualStudio.Debugger.Native; namespace nullc_debugger_component { namespace DkmDebugger { static class DebugHelpers { public static readonly bool useNativeInterfaces = true; public static readonly bool useDefaultRuntimeInstance = false; public static readonly bool checkVmModuleDocuments = false; public static readonly Guid NullcSymbolProviderGuid = new Guid("BF13BE48-BE1A-4424-B961-BFC40C71E58A"); public static readonly Guid NullcCompilerGuid = new Guid("A7CB5F2B-CD45-4CF4-9CB6-61A30968EFB5"); public static readonly Guid NullcLanguageGuid = new Guid("9221BA37-3FB0-483A-BD6A-0E5DD22E107E"); public static readonly Guid NullcRuntimeGuid = new Guid("3AF14FEA-CB31-4DBB-90E5-74BF685CA7B8"); public static readonly Guid NullcCallStackDataBaseGuid = new Guid("E0838372-9E1B-4ED0-B687-60F0396DC91E"); public static readonly Guid NullcStepperBreakpointSourceId = new Guid("4E7147D0-6375-4962-A2BF-651F802E27D7"); public static readonly Guid NullcReloadSymbolsMessageGuid = new Guid("3E039B2A-7B89-4801-B2F3-D0A50243246E"); public static readonly Guid NullcVmRuntimeGuid = new Guid("3CD8BDDA-B50C-4914-8583-78320E3311A9"); //public static readonly Guid NullcSymbolProviderFilterGuid = new Guid("0B2E28CC-D574-461C-90F4-0C251AA71DE8"); internal static T GetOrCreateDataItem<T>(DkmDataContainer container) where T : DkmDataItem, new() { T item = container.GetDataItem<T>(); if (item != null) { return item; } item = new T(); container.SetDataItem<T>(DkmDataCreationDisposition.CreateNew, item); return item; } internal static string FindFunctionAddress(DkmRuntimeInstance runtimeInstance, string name) { string result = null; foreach (var module in runtimeInstance.GetModuleInstances()) { var address = (module as DkmNativeModuleInstance)?.FindExportName(name, IgnoreDataExports: true); if (address != null) { result = $"0x{address.CPUInstructionPart.InstructionPointer:X}"; break; } } return result; } internal static bool Is64Bit(DkmProcess process) { return (process.SystemInformation.Flags & DkmSystemInformationFlags.Is64Bit) != 0; } internal static int GetPointerSize(DkmProcess process) { return Is64Bit(process) ? 8 : 4; } internal static byte? ReadByteVariable(DkmProcess process, ulong address) { byte[] variableAddressData = new byte[1]; // ReadMemory should check for invalid pages, but it still throws an exception on small adresses in practice if (address < 0x0001000) { return null; } if (process.ReadMemory(address, DkmReadMemoryFlags.None, variableAddressData) == 0) { return null; } return variableAddressData[0]; } internal static short? ReadShortVariable(DkmProcess process, ulong address) { byte[] variableAddressData = new byte[2]; // ReadMemory should check for invalid pages, but it still throws an exception on small adresses in practice if (address < 0x0001000) { return null; } if (process.ReadMemory(address, DkmReadMemoryFlags.None, variableAddressData) == 0) { return null; } return BitConverter.ToInt16(variableAddressData, 0); } internal static int? ReadIntVariable(DkmProcess process, ulong address) { byte[] variableAddressData = new byte[4]; // ReadMemory should check for invalid pages, but it still throws an exception on small adresses in practice if (address < 0x0001000) { return null; } if (process.ReadMemory(address, DkmReadMemoryFlags.None, variableAddressData) == 0) { return null; } return BitConverter.ToInt32(variableAddressData, 0); } internal static uint? ReadUintVariable(DkmProcess process, ulong address) { byte[] variableAddressData = new byte[4]; // ReadMemory should check for invalid pages, but it still throws an exception on small adresses in practice if (address < 0x0001000) { return null; } if (process.ReadMemory(address, DkmReadMemoryFlags.None, variableAddressData) == 0) { return null; } return BitConverter.ToUInt32(variableAddressData, 0); } internal static long? ReadLongVariable(DkmProcess process, ulong address) { byte[] variableAddressData = new byte[8]; // ReadMemory should check for invalid pages, but it still throws an exception on small adresses in practice if (address < 0x0001000) { return null; } if (process.ReadMemory(address, DkmReadMemoryFlags.None, variableAddressData) == 0) { return null; } return BitConverter.ToInt64(variableAddressData, 0); } internal static ulong? ReadUlongVariable(DkmProcess process, ulong address) { byte[] variableAddressData = new byte[8]; // ReadMemory should check for invalid pages, but it still throws an exception on small adresses in practice if (address < 0x0001000) { return null; } if (process.ReadMemory(address, DkmReadMemoryFlags.None, variableAddressData) == 0) { return null; } return BitConverter.ToUInt64(variableAddressData, 0); } internal static float? ReadFloatVariable(DkmProcess process, ulong address) { byte[] variableAddressData = new byte[4]; // ReadMemory should check for invalid pages, but it still throws an exception on small adresses in practice if (address < 0x0001000) { return null; } if (process.ReadMemory(address, DkmReadMemoryFlags.None, variableAddressData) == 0) { return null; } return BitConverter.ToSingle(variableAddressData, 0); } internal static double? ReadDoubleVariable(DkmProcess process, ulong address) { byte[] variableAddressData = new byte[8]; // ReadMemory should check for invalid pages, but it still throws an exception on small adresses in practice if (address < 0x0001000) { return null; } if (process.ReadMemory(address, DkmReadMemoryFlags.None, variableAddressData) == 0) { return null; } return BitConverter.ToDouble(variableAddressData, 0); } internal static ulong? ReadPointerVariable(DkmProcess process, ulong address) { if (!Is64Bit(process)) { return ReadUintVariable(process, address); } return ReadUlongVariable(process, address); } internal static ulong? ReadPointerVariable(DkmProcess process, string name) { var runtimeInstance = process.GetNativeRuntimeInstance(); if (runtimeInstance != null) { foreach (var module in runtimeInstance.GetModuleInstances()) { var nativeModule = module as DkmNativeModuleInstance; var variableAddress = nativeModule?.FindExportName(name, IgnoreDataExports: false); if (variableAddress != null) { return ReadPointerVariable(process, variableAddress.CPUInstructionPart.InstructionPointer); } } } return null; } internal static bool TryWriteVariable(DkmProcess process, ulong address, byte value) { try { process.WriteMemory(address, new byte[1] { value }); } catch (Exception) { return false; } return true; } internal static bool TryWriteVariable(DkmProcess process, ulong address, short value) { try { process.WriteMemory(address, BitConverter.GetBytes(value)); } catch (Exception) { return false; } return true; } internal static bool TryWriteVariable(DkmProcess process, ulong address, int value) { try { process.WriteMemory(address, BitConverter.GetBytes(value)); } catch (Exception) { return false; } return true; } internal static bool TryWriteVariable(DkmProcess process, ulong address, long value) { try { process.WriteMemory(address, BitConverter.GetBytes(value)); } catch (Exception) { return false; } return true; } internal static bool TryWriteVariable(DkmProcess process, ulong address, float value) { try { process.WriteMemory(address, BitConverter.GetBytes(value)); } catch (Exception) { return false; } return true; } internal static bool TryWriteVariable(DkmProcess process, ulong address, double value) { try { process.WriteMemory(address, BitConverter.GetBytes(value)); } catch (Exception) { return false; } return true; } } } }
using UnityEngine; //using Windows.Kinect; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.IO; using System.Text; /// <summary> /// Avatar controller is the component that transfers the captured user motion to a humanoid model (avatar). /// </summary> [RequireComponent(typeof(Animator))] public class AvatarController : MonoBehaviour { [Tooltip("Index of the player, tracked by this component. 0 means the 1st player, 1 - the 2nd one, 2 - the 3rd one, etc.")] public int playerIndex = 0; [Tooltip("Whether the avatar is facing the player or not.")] public bool mirroredMovement = false; [Tooltip("Whether the avatar is allowed to move vertically or not.")] public bool verticalMovement = false; [Tooltip("Rate at which the avatar will move through the scene.")] public float moveRate = 1f; [Tooltip("Smooth factor used for avatar movements and joint rotations.")] public float smoothFactor = 5f; [Tooltip("Game object this transform is relative to (optional).")] public GameObject offsetNode; [Tooltip("If specified, makes the initial avatar position relative to this camera, to be equal to the player's position relative to the sensor.")] public Camera posRelativeToCamera; // The body root node protected Transform bodyRoot; // Variable to hold all them bones. It will initialize the same size as initialRotations. protected Transform[] bones; // Rotations of the bones when the Kinect tracking starts. protected Quaternion[] initialRotations; // Initial position and rotation of the transform protected Vector3 initialPosition; protected Quaternion initialRotation; protected Vector3 offsetNodePos; protected Quaternion offsetNodeRot; protected Vector3 bodyRootPosition; // Calibration Offset Variables for Character Position. protected bool offsetCalibrated = false; protected float xOffset, yOffset, zOffset; //private Quaternion originalRotation; // whether the parent transform obeys physics protected bool isRigidBody = false; // private instance of the KinectManager protected KinectManager kinectManager; // returns the number of bone transforms (array length) public int GetBoneTransformCount() { return bones != null ? bones.Length : 0; } // returns the bone transform by index public Transform GetBoneTransform(int index) { if(index >= 0 && index < bones.Length) { return bones[index]; } return null; } // transform caching gives performance boost since Unity calls GetComponent<Transform>() each time you call transform private Transform _transformCache; public new Transform transform { get { if (!_transformCache) _transformCache = base.transform; return _transformCache; } } public void Awake() { // check for double start if(bones != null) return; if(!gameObject.activeInHierarchy) return; // inits the bones array bones = new Transform[27]; // Initial rotations and directions of the bones. initialRotations = new Quaternion[bones.Length]; // Map bones to the points the Kinect tracks MapBones(); // Get initial bone rotations GetInitialRotations(); // if parent transform uses physics isRigidBody = gameObject.GetComponent<Rigidbody>(); } // Update the avatar each frame. public void UpdateAvatar(Int64 UserID) { if(!gameObject.activeInHierarchy) return; // Get the KinectManager instance if(kinectManager == null) { kinectManager = KinectManager.Instance; } // move the avatar to its Kinect position MoveAvatar(UserID); for (var boneIndex = 0; boneIndex < bones.Length; boneIndex++) { if (!bones[boneIndex]) continue; if(boneIndex2JointMap.ContainsKey(boneIndex)) { KinectInterop.JointType joint = !mirroredMovement ? boneIndex2JointMap[boneIndex] : boneIndex2MirrorJointMap[boneIndex]; TransformBone(UserID, joint, boneIndex, !mirroredMovement); } else if(specIndex2JointMap.ContainsKey(boneIndex)) { // special bones (clavicles) List<KinectInterop.JointType> alJoints = !mirroredMovement ? specIndex2JointMap[boneIndex] : specIndex2MirrorJointMap[boneIndex]; if(alJoints.Count >= 2) { //Debug.Log(alJoints[0].ToString()); Vector3 baseDir = alJoints[0].ToString().EndsWith("Left") ? Vector3.left : Vector3.right; TransformSpecialBone(UserID, alJoints[0], alJoints[1], boneIndex, baseDir, !mirroredMovement); } } } } // Set bones to their initial positions and rotations. public void ResetToInitialPosition() { if(bones == null) return; // For each bone that was defined, reset to initial position. transform.rotation = Quaternion.identity; for(int pass = 0; pass < 2; pass++) // 2 passes because clavicles are at the end { for(int i = 0; i < bones.Length; i++) { if(bones[i] != null) { bones[i].rotation = initialRotations[i]; } } } // if(bodyRoot != null) // { // bodyRoot.localPosition = Vector3.zero; // bodyRoot.localRotation = Quaternion.identity; // } // Restore the offset's position and rotation if(offsetNode != null) { offsetNode.transform.position = offsetNodePos; offsetNode.transform.rotation = offsetNodeRot; } transform.position = initialPosition; transform.rotation = initialRotation; } // Invoked on the successful calibration of a player. public void SuccessfulCalibration(Int64 userId) { // reset the models position if(offsetNode != null) { offsetNode.transform.position = offsetNodePos; offsetNode.transform.rotation = offsetNodeRot; } transform.position = initialPosition; transform.rotation = initialRotation; // re-calibrate the position offset offsetCalibrated = false; } // Apply the rotations tracked by kinect to the joints. protected void TransformBone(Int64 userId, KinectInterop.JointType joint, int boneIndex, bool flip) { Transform boneTransform = bones[boneIndex]; if(boneTransform == null || kinectManager == null) return; int iJoint = (int)joint; if(iJoint < 0 || !kinectManager.IsJointTracked(userId, iJoint)) return; // Get Kinect joint orientation Quaternion jointRotation = kinectManager.GetJointOrientation(userId, iJoint, flip); if(jointRotation == Quaternion.identity) return; // Smoothly transition to the new rotation Quaternion newRotation = Kinect2AvatarRot(jointRotation, boneIndex); if(smoothFactor != 0f) boneTransform.rotation = Quaternion.Slerp(boneTransform.rotation, newRotation, smoothFactor * Time.deltaTime); else boneTransform.rotation = newRotation; } // Apply the rotations tracked by kinect to a special joint protected void TransformSpecialBone(Int64 userId, KinectInterop.JointType joint, KinectInterop.JointType jointParent, int boneIndex, Vector3 baseDir, bool flip) { Transform boneTransform = bones[boneIndex]; if(boneTransform == null || kinectManager == null) return; if(!kinectManager.IsJointTracked(userId, (int)joint) || !kinectManager.IsJointTracked(userId, (int)jointParent)) { return; } Vector3 jointDir = kinectManager.GetJointDirection(userId, (int)joint, false, true); Quaternion jointRotation = jointDir != Vector3.zero ? Quaternion.FromToRotation(baseDir, jointDir) : Quaternion.identity; if(!flip) { Vector3 mirroredAngles = jointRotation.eulerAngles; mirroredAngles.y = -mirroredAngles.y; mirroredAngles.z = -mirroredAngles.z; jointRotation = Quaternion.Euler(mirroredAngles); } if(jointRotation != Quaternion.identity) { // Smoothly transition to the new rotation Quaternion newRotation = Kinect2AvatarRot(jointRotation, boneIndex); if(smoothFactor != 0f) boneTransform.rotation = Quaternion.Slerp(boneTransform.rotation, newRotation, smoothFactor * Time.deltaTime); else boneTransform.rotation = newRotation; } } // Moves the avatar in 3D space - pulls the tracked position of the user and applies it to root. protected void MoveAvatar(Int64 UserID) { if(!kinectManager || !kinectManager.IsJointTracked(UserID, (int)KinectInterop.JointType.SpineBase)) return; // Get the position of the body and store it. Vector3 trans = kinectManager.GetUserPosition(UserID); // If this is the first time we're moving the avatar, set the offset. Otherwise ignore it. if (!offsetCalibrated) { offsetCalibrated = true; xOffset = trans.x; // !mirroredMovement ? trans.x * moveRate : -trans.x * moveRate; yOffset = trans.y; // trans.y * moveRate; zOffset = !mirroredMovement ? -trans.z : trans.z; // -trans.z * moveRate; if(posRelativeToCamera) { Vector3 cameraPos = posRelativeToCamera.transform.position; Vector3 bodyRootPos = bodyRoot != null ? bodyRoot.position : transform.position; Vector3 hipCenterPos = bodyRoot != null ? bodyRoot.position : bones[0].position; float yRelToAvatar = 0f; if(verticalMovement) { yRelToAvatar = (trans.y - cameraPos.y) - (hipCenterPos - bodyRootPos).magnitude; } else { yRelToAvatar = bodyRootPos.y - cameraPos.y; } Vector3 relativePos = new Vector3(trans.x, yRelToAvatar, trans.z); Vector3 newBodyRootPos = cameraPos + relativePos; // if(offsetNode != null) // { // newBodyRootPos += offsetNode.transform.position; // } if(bodyRoot != null) { bodyRoot.position = newBodyRootPos; } else { transform.position = newBodyRootPos; } bodyRootPosition = newBodyRootPos; } } // Smoothly transition to the new position Vector3 targetPos = bodyRootPosition + Kinect2AvatarPos(trans, verticalMovement); if(isRigidBody && !verticalMovement) { // workaround for obeying the physics (e.g. gravity falling) targetPos.y = bodyRoot != null ? bodyRoot.position.y : transform.position.y; } if(bodyRoot != null) { bodyRoot.position = smoothFactor != 0f ? Vector3.Lerp(bodyRoot.position, targetPos, smoothFactor * Time.deltaTime) : targetPos; } else { transform.position = smoothFactor != 0f ? Vector3.Lerp(transform.position, targetPos, smoothFactor * Time.deltaTime) : targetPos; } } // If the bones to be mapped have been declared, map that bone to the model. protected virtual void MapBones() { // // make OffsetNode as a parent of model transform. // offsetNode = new GameObject(name + "Ctrl") { layer = transform.gameObject.layer, tag = transform.gameObject.tag }; // offsetNode.transform.position = transform.position; // offsetNode.transform.rotation = transform.rotation; // offsetNode.transform.parent = transform.parent; // // take model transform as body root // transform.parent = offsetNode.transform; // transform.localPosition = Vector3.zero; // transform.localRotation = Quaternion.identity; //bodyRoot = transform; // get bone transforms from the animator component Animator animatorComponent = GetComponent<Animator>(); for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++) { if (!boneIndex2MecanimMap.ContainsKey(boneIndex)) continue; bones[boneIndex] = animatorComponent.GetBoneTransform(boneIndex2MecanimMap[boneIndex]); } } // Capture the initial rotations of the bones protected void GetInitialRotations() { // save the initial rotation if(offsetNode != null) { offsetNodePos = offsetNode.transform.position; offsetNodeRot = offsetNode.transform.rotation; } initialPosition = transform.position; initialRotation = transform.rotation; // if(offsetNode != null) // { // initialRotation = Quaternion.Inverse(offsetNodeRot) * initialRotation; // } transform.rotation = Quaternion.identity; // save the body root initial position if(bodyRoot != null) { bodyRootPosition = bodyRoot.position; } else { bodyRootPosition = transform.position; } if(offsetNode != null) { bodyRootPosition = bodyRootPosition - offsetNodePos; } // save the initial bone rotations for (int i = 0; i < bones.Length; i++) { if (bones[i] != null) { initialRotations[i] = bones[i].rotation; } } // Restore the initial rotation transform.rotation = initialRotation; } // Converts kinect joint rotation to avatar joint rotation, depending on joint initial rotation and offset rotation protected Quaternion Kinect2AvatarRot(Quaternion jointRotation, int boneIndex) { Quaternion newRotation = jointRotation * initialRotations[boneIndex]; //newRotation = initialRotation * newRotation; if(offsetNode != null) { newRotation = offsetNode.transform.rotation * newRotation; } else { newRotation = initialRotation * newRotation; } return newRotation; } // Converts Kinect position to avatar skeleton position, depending on initial position, mirroring and move rate protected Vector3 Kinect2AvatarPos(Vector3 jointPosition, bool bMoveVertically) { float xPos; // if(!mirroredMovement) xPos = (jointPosition.x - xOffset) * moveRate; // else // xPos = (-jointPosition.x - xOffset) * moveRate; float yPos = (jointPosition.y - yOffset) * moveRate; //float zPos = (-jointPosition.z - zOffset) * moveRate; float zPos = !mirroredMovement ? (-jointPosition.z - zOffset) * moveRate : (jointPosition.z - zOffset) * moveRate; Vector3 newPosition = new Vector3(xPos, bMoveVertically ? yPos : 0f, zPos); if(offsetNode != null) { newPosition += offsetNode.transform.position; } return newPosition; } // protected void OnCollisionEnter(Collision col) // { // Debug.Log("Collision entered"); // } // // protected void OnCollisionExit(Collision col) // { // Debug.Log("Collision exited"); // } // dictionaries to speed up bones' processing // the author of the terrific idea for kinect-joints to mecanim-bones mapping // along with its initial implementation, including following dictionary is // Mikhail Korchun (korchoon@gmail.com). Big thanks to this guy! private readonly Dictionary<int, HumanBodyBones> boneIndex2MecanimMap = new Dictionary<int, HumanBodyBones> { {0, HumanBodyBones.Hips}, {1, HumanBodyBones.Spine}, // {2, HumanBodyBones.Chest}, {3, HumanBodyBones.Neck}, // {4, HumanBodyBones.Head}, {5, HumanBodyBones.LeftUpperArm}, {6, HumanBodyBones.LeftLowerArm}, {7, HumanBodyBones.LeftHand}, {8, HumanBodyBones.LeftIndexProximal}, // {9, HumanBodyBones.LeftIndexIntermediate}, // {10, HumanBodyBones.LeftThumbProximal}, {11, HumanBodyBones.RightUpperArm}, {12, HumanBodyBones.RightLowerArm}, {13, HumanBodyBones.RightHand}, {14, HumanBodyBones.RightIndexProximal}, // {15, HumanBodyBones.RightIndexIntermediate}, // {16, HumanBodyBones.RightThumbProximal}, {17, HumanBodyBones.LeftUpperLeg}, {18, HumanBodyBones.LeftLowerLeg}, {19, HumanBodyBones.LeftFoot}, // {20, HumanBodyBones.LeftToes}, {21, HumanBodyBones.RightUpperLeg}, {22, HumanBodyBones.RightLowerLeg}, {23, HumanBodyBones.RightFoot}, // {24, HumanBodyBones.RightToes}, {25, HumanBodyBones.LeftShoulder}, {26, HumanBodyBones.RightShoulder}, }; protected readonly Dictionary<int, KinectInterop.JointType> boneIndex2JointMap = new Dictionary<int, KinectInterop.JointType> { {0, KinectInterop.JointType.SpineBase}, {1, KinectInterop.JointType.SpineMid}, {2, KinectInterop.JointType.SpineShoulder}, {3, KinectInterop.JointType.Neck}, {4, KinectInterop.JointType.Head}, {5, KinectInterop.JointType.ShoulderLeft}, {6, KinectInterop.JointType.ElbowLeft}, {7, KinectInterop.JointType.WristLeft}, {8, KinectInterop.JointType.HandLeft}, {9, KinectInterop.JointType.HandTipLeft}, {10, KinectInterop.JointType.ThumbLeft}, {11, KinectInterop.JointType.ShoulderRight}, {12, KinectInterop.JointType.ElbowRight}, {13, KinectInterop.JointType.WristRight}, {14, KinectInterop.JointType.HandRight}, {15, KinectInterop.JointType.HandTipRight}, {16, KinectInterop.JointType.ThumbRight}, {17, KinectInterop.JointType.HipLeft}, {18, KinectInterop.JointType.KneeLeft}, {19, KinectInterop.JointType.AnkleLeft}, {20, KinectInterop.JointType.FootLeft}, {21, KinectInterop.JointType.HipRight}, {22, KinectInterop.JointType.KneeRight}, {23, KinectInterop.JointType.AnkleRight}, {24, KinectInterop.JointType.FootRight}, }; protected readonly Dictionary<int, List<KinectInterop.JointType>> specIndex2JointMap = new Dictionary<int, List<KinectInterop.JointType>> { {25, new List<KinectInterop.JointType> {KinectInterop.JointType.ShoulderLeft, KinectInterop.JointType.SpineShoulder} }, {26, new List<KinectInterop.JointType> {KinectInterop.JointType.ShoulderRight, KinectInterop.JointType.SpineShoulder} }, }; protected readonly Dictionary<int, KinectInterop.JointType> boneIndex2MirrorJointMap = new Dictionary<int, KinectInterop.JointType> { {0, KinectInterop.JointType.SpineBase}, {1, KinectInterop.JointType.SpineMid}, {2, KinectInterop.JointType.SpineShoulder}, {3, KinectInterop.JointType.Neck}, {4, KinectInterop.JointType.Head}, {5, KinectInterop.JointType.ShoulderRight}, {6, KinectInterop.JointType.ElbowRight}, {7, KinectInterop.JointType.WristRight}, {8, KinectInterop.JointType.HandRight}, {9, KinectInterop.JointType.HandTipRight}, {10, KinectInterop.JointType.ThumbRight}, {11, KinectInterop.JointType.ShoulderLeft}, {12, KinectInterop.JointType.ElbowLeft}, {13, KinectInterop.JointType.WristLeft}, {14, KinectInterop.JointType.HandLeft}, {15, KinectInterop.JointType.HandTipLeft}, {16, KinectInterop.JointType.ThumbLeft}, {17, KinectInterop.JointType.HipRight}, {18, KinectInterop.JointType.KneeRight}, {19, KinectInterop.JointType.AnkleRight}, {20, KinectInterop.JointType.FootRight}, {21, KinectInterop.JointType.HipLeft}, {22, KinectInterop.JointType.KneeLeft}, {23, KinectInterop.JointType.AnkleLeft}, {24, KinectInterop.JointType.FootLeft}, }; protected readonly Dictionary<int, List<KinectInterop.JointType>> specIndex2MirrorJointMap = new Dictionary<int, List<KinectInterop.JointType>> { {25, new List<KinectInterop.JointType> {KinectInterop.JointType.ShoulderRight, KinectInterop.JointType.SpineShoulder} }, {26, new List<KinectInterop.JointType> {KinectInterop.JointType.ShoulderLeft, KinectInterop.JointType.SpineShoulder} }, }; }
// 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.Xml; using System.Collections; using System.Diagnostics; using System.Runtime.Serialization; using System.Collections.Generic; using System.Collections.ObjectModel; namespace System.Xml { public class XmlBinaryWriterSession { private PriorityDictionary<string, int> _strings; private PriorityDictionary<IXmlDictionary, IntArray> _maps; private int _nextKey; public XmlBinaryWriterSession() { _nextKey = 0; _maps = new PriorityDictionary<IXmlDictionary, IntArray>(); _strings = new PriorityDictionary<string, int>(); } public virtual bool TryAdd(XmlDictionaryString value, out int key) { IntArray keys; if (value == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); if (_maps.TryGetValue(value.Dictionary, out keys)) { key = (keys[value.Key] - 1); if (key != -1) { // If the key is already set, then something is wrong throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlKeyAlreadyExists))); } key = Add(value.Value); keys[value.Key] = (key + 1); return true; } key = Add(value.Value); keys = AddKeys(value.Dictionary, value.Key + 1); keys[value.Key] = (key + 1); return true; } private int Add(string s) { int key = _nextKey++; _strings.Add(s, key); return key; } private IntArray AddKeys(IXmlDictionary dictionary, int minCount) { IntArray keys = new IntArray(Math.Max(minCount, 16)); _maps.Add(dictionary, keys); return keys; } public void Reset() { _nextKey = 0; _maps.Clear(); _strings.Clear(); } internal bool TryLookup(XmlDictionaryString s, out int key) { IntArray keys; if (_maps.TryGetValue(s.Dictionary, out keys)) { key = (keys[s.Key] - 1); if (key != -1) { return true; } } if (_strings.TryGetValue(s.Value, out key)) { if (keys == null) { keys = AddKeys(s.Dictionary, s.Key + 1); } keys[s.Key] = (key + 1); return true; } key = -1; return false; } private class PriorityDictionary<K, V> where K : class { private Dictionary<K, V> _dictionary; private Entry[] _list; private int _listCount; private int _now; public PriorityDictionary() { _list = new Entry[16]; } public void Clear() { _now = 0; _listCount = 0; Array.Clear(_list, 0, _list.Length); if (_dictionary != null) _dictionary.Clear(); } public bool TryGetValue(K key, out V value) { for (int i = 0; i < _listCount; i++) { if (_list[i].Key == key) { value = _list[i].Value; _list[i].Time = Now; return true; } } for (int i = 0; i < _listCount; i++) { if (_list[i].Key.Equals(key)) { value = _list[i].Value; _list[i].Time = Now; return true; } } if (_dictionary == null) { value = default(V); return false; } if (!_dictionary.TryGetValue(key, out value)) { return false; } int minIndex = 0; int minTime = _list[0].Time; for (int i = 1; i < _listCount; i++) { if (_list[i].Time < minTime) { minIndex = i; minTime = _list[i].Time; } } _list[minIndex].Key = key; _list[minIndex].Value = value; _list[minIndex].Time = Now; return true; } public void Add(K key, V value) { if (_listCount < _list.Length) { _list[_listCount].Key = key; _list[_listCount].Value = value; _listCount++; } else { if (_dictionary == null) { _dictionary = new Dictionary<K, V>(); for (int i = 0; i < _listCount; i++) { _dictionary.Add(_list[i].Key, _list[i].Value); } } _dictionary.Add(key, value); } } private int Now { get { if (++_now == int.MaxValue) { DecreaseAll(); } return _now; } } private void DecreaseAll() { for (int i = 0; i < _listCount; i++) { _list[i].Time /= 2; } _now /= 2; } private struct Entry { public K Key; public V Value; public int Time; } } private class IntArray { private int[] _array; public IntArray(int size) { _array = new int[size]; } public int this[int index] { get { if (index >= _array.Length) return 0; return _array[index]; } set { if (index >= _array.Length) { int[] newArray = new int[Math.Max(index + 1, _array.Length * 2)]; Array.Copy(_array, newArray, _array.Length); _array = newArray; } _array[index] = value; } } } } }
using Android.Content; using Android.Hardware; using Android.Util; using Android.Views; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace Camdro { /// <summary> /// A simple wrapper around a Camera and a SurfaceView that renders a centered preview of the Camera /// to the surface. We need to center the SurfaceView because not all devices have cameras that /// support preview sizes at the same aspect ratio as the device's display. /// /// Adapted from https://github.com/xamarin/monodroid-samples/blob/master/ApiDemo/Graphics/CameraPreview.cs /// </summary> public class Viewfinder : ViewGroup, ISurfaceHolderCallback, Camera.IPictureCallback { Camera _camera; int _deviceOrientation; int _displayOrientation; bool _quarterTurn = false; bool _openedOrOpening = false; public Viewfinder(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { Init(context); } public Viewfinder(Context context, IAttributeSet attrs) : base(context, attrs) { Init(context); } public Viewfinder(Context context) : base(context) { Init(context); } private void Init(Context context) { // Get the current orientation of the device switch (((Android.App.Activity)context).WindowManager.DefaultDisplay.Rotation) { case SurfaceOrientation.Rotation90: _deviceOrientation = 90; break; case SurfaceOrientation.Rotation180: _deviceOrientation = 180; break; case SurfaceOrientation.Rotation270: _deviceOrientation = 270; break; default: _deviceOrientation = 0; break; } var surfaceView = new SurfaceView(context); AddView(surfaceView); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. surfaceView.Holder.AddCallback(this); } /// <summary> /// Open the camera. /// </summary> /// <returns>The opened camera.</returns> private Camera OpenCameraFunc(out int cameraOrientation) { Camera camera = null; cameraOrientation = 0; var cameraInfo = new Camera.CameraInfo(); int cameraCount = Camera.NumberOfCameras; for (int camId = 0; camId < cameraCount; camId++) { Camera.GetCameraInfo(camId, cameraInfo); if (cameraInfo.Facing == CameraFacing.Back) { try { camera = Camera.Open(camId); cameraOrientation = cameraInfo.Orientation; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Exception in OpenCamera {0}", ex, null); } } } return camera; } public bool OpenCamera() { // Release the current camera being previewed if there is one ReleaseCamera(); _openedOrOpening = true; int cameraOrientation; var camera = OpenCameraFunc(out cameraOrientation); // Camera not found if (camera == null) { _openedOrOpening = false; return false; } // ReleaseCamera was already called if (!_openedOrOpening) { camera.Release(); return false; } _camera = camera; _displayOrientation = (cameraOrientation - _deviceOrientation + 360) % 360; // Check if the camera orientation is perpendicular to the device orientation _quarterTurn = (_displayOrientation == 90 || _displayOrientation == 270); ((Android.App.Activity)Context).RunOnUiThread(RequestLayout); return true; } public async Task<bool> OpenCameraAsync() { return await Task.Run(() => OpenCamera()); } public void ReleaseCamera() { _openedOrOpening = false; var camera = _camera; if (camera != null) { try { StopPreview(); camera.Release(); _camera = null; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Exception in ReleaseCamera {0}", ex, null); } } } protected override void OnLayout(bool changed, int l, int t, int r, int b) { if (ChildCount == 0) { return; } var camera = _camera; if (camera == null) { return; } View child = GetChildAt(0); int width = r - l; int height = b - t; var parameters = camera.GetParameters(); var sizes = parameters.SupportedPreviewSizes; var previewSize = GetOptimalSize(sizes, width, height, _quarterTurn); parameters.SetPreviewSize(previewSize.Width, previewSize.Height); camera.SetParameters(parameters); int surfaceWidth, surfaceHeight; if (_quarterTurn) { surfaceWidth = previewSize.Height; surfaceHeight = previewSize.Width; } else { surfaceWidth = previewSize.Width; surfaceHeight = previewSize.Height; } if (surfaceHeight == 0 || surfaceHeight == 0) { return; } // Center the child SurfaceView within the parent. if (width * surfaceHeight > height * surfaceWidth) { int scaledChildWidth = surfaceWidth * height / surfaceHeight; child.Layout((width - scaledChildWidth) / 2, 0, (width + scaledChildWidth) / 2, height); } else { int scaledChildHeight = surfaceHeight * width / surfaceWidth; child.Layout(0, (height - scaledChildHeight) / 2, width, (height + scaledChildHeight) / 2); } } /// <summary> /// Return the size from sizes which has the same aspect w/h and is closest in height to h. /// If no sizes are the same aspect, then return the one closest in height to h. /// </summary> /// <param name="sizes">List of picture sizes.</param> /// <param name="w">Width of the target.</param> /// <param name="h">Height of the target.</param> /// <param name="quarterTurn">If true, then w and h are swapped before calculation.</param> private Camera.Size GetOptimalSize(IList<Camera.Size> sizes, int w, int h, bool quarterTurn) { if (sizes == null) { return null; } // Swap width and height if camera orientation is perpendicular to device orientation if (quarterTurn) { var w2 = w; w = h; h = w2; } const double ASPECT_TOLERANCE = 0.1; double targetRatio = (double)w / h; Camera.Size optimalSize = null; double minDiff = Double.MaxValue; int targetHeight = h; int previewWidth, previewHeight; // Try to find an size match aspect ratio and size foreach (var size in sizes) { previewHeight = size.Height; previewWidth = size.Width; double ratio = (double)previewWidth / previewHeight; if (Math.Abs(ratio - targetRatio) > ASPECT_TOLERANCE) { continue; } if (Math.Abs(previewHeight - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.Abs(previewHeight - targetHeight); } } // Cannot find size matching the aspect ratio, ignore the requirement if (optimalSize == null) { minDiff = Double.MaxValue; foreach (var size in sizes) { previewHeight = size.Height; if (Math.Abs(previewHeight - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.Abs(previewHeight - targetHeight); } } } return optimalSize; } /* * ISurfaceHolderCallback implementation */ private ISurfaceHolder _surfaceHolder; public void SurfaceCreated(ISurfaceHolder holder) { _surfaceHolder = holder; if (_previewStarted) { StartPreview(); } } public void SurfaceDestroyed(ISurfaceHolder holder) { // Surface will be destroyed when we return, so stop the preview. StopPreview(); } public void SurfaceChanged(ISurfaceHolder holder, Android.Graphics.Format format, int w, int h) { } /* * Camera functions */ bool _previewStarted; /// <summary> /// Start the camera preview on the surface. /// </summary> /// <returns>True if the preview could be started.</returns> public bool StartPreview() { return StartPreview(_camera); } private bool StartPreview(Camera camera) { if (camera == null) { return false; } StopPreview(camera); // Mark preview as started if surface holder not yet created. We will really start it later _previewStarted = true; if (_surfaceHolder == null) { return false; } camera.SetDisplayOrientation(_displayOrientation); camera.SetPreviewDisplay(_surfaceHolder); try { camera.StartPreview(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("StartPreview {0}", ex); return false; } return true; } public void StopPreview() { StopPreview(_camera); } private void StopPreview(Camera camera) { if (camera == null) { return; } _previewStarted = false; try { camera.StopPreview(); } catch (Exception) { // ignore: tried to stop a non-existent preview } } /// <summary> /// Async method to run when the picture is available. /// The method may use <see cref="WriteDataToStream" /> to write the data. /// The written file should be saved with the ext parameter. /// </summary> public delegate Task PictureAvailableHandler(byte[] data); private PictureAvailableHandler _pictureAvailable; /// <summary> /// Take a picture. /// </summary> /// <param name="pictureAvailable">Delegate to run when picture is available.</param> /// <returns>True if the picture could be taken.</returns> public bool TakePicture(PictureAvailableHandler pictureAvailable) { if (_camera != null) { try { var parameters = _camera.GetParameters(); var sizes = parameters.SupportedPictureSizes; var pictureSize = GetOptimalSize(sizes, 640, 480, false); parameters.SetRotation(_displayOrientation); parameters.SetPictureSize(pictureSize.Width, pictureSize.Height); _camera.SetParameters(parameters); _pictureAvailable = pictureAvailable; _camera.TakePicture(null, null, this); return true; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("TakePicture {0}", ex); } } return false; } /// <summary> /// Write picture data to stream. The picture will be rotated if necessary. /// </summary> public async Task WriteDataToStream(byte[] data, Stream writeStream) { var rotate = _displayOrientation; if (rotate == 0) { using (var ms = new MemoryStream(data)) { await ms.CopyToAsync(writeStream); } } else { using (var sourceBm = await Android.Graphics.BitmapFactory.DecodeByteArrayAsync(data, 0, data.Length)) { using (var m = new Android.Graphics.Matrix()) { m.PostRotate(rotate); using (var bm = Android.Graphics.Bitmap.CreateBitmap(sourceBm, 0, 0, sourceBm.Width, sourceBm.Height, m, true)) { if (sourceBm != bm) { sourceBm.Recycle(); } await bm.CompressAsync(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, writeStream); bm.Recycle(); } } } } } /* * IPictureCallback implementation */ public async void OnPictureTaken(byte[] data, Camera cam) { await _pictureAvailable(data); } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.Common; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; namespace PCSComUtils.MasterSetup.DS { public class MST_TransactionHistoryDS { public MST_TransactionHistoryDS() { } private const string THIS = "PCSComUtils.MasterSetup.DS.MST_TransactionHistoryDS"; /// <summary> /// This method uses to add data to MST_TransactionHistory /// </summary> /// <param name="pobjObjectVO">MST_TransactionHistoryVO</param> public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { MST_TransactionHistoryVO objObject = (MST_TransactionHistoryVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql = "INSERT INTO " + MST_TransactionHistoryTable.TABLE_NAME + "(" + MST_TransactionHistoryTable.MASTERLOCATIONID_FLD + "," + MST_TransactionHistoryTable.BINID_FLD + "," + MST_TransactionHistoryTable.BUYSELLCOST_FLD + "," + MST_TransactionHistoryTable.INSPSTATUS_FLD + "," + MST_TransactionHistoryTable.TRANSDATE_FLD + "," + MST_TransactionHistoryTable.POSTDATE_FLD + "," + MST_TransactionHistoryTable.REFMASTERID_FLD + "," + MST_TransactionHistoryTable.REFDETAILID_FLD + "," + MST_TransactionHistoryTable.COST_FLD + "," + MST_TransactionHistoryTable.CCNID_FLD + "," + MST_TransactionHistoryTable.TRANTYPEID_FLD + "," + MST_TransactionHistoryTable.PARTYID_FLD + "," + MST_TransactionHistoryTable.PARTYLOCATIONID_FLD + "," + MST_TransactionHistoryTable.LOCATIONID_FLD + "," + MST_TransactionHistoryTable.PRODUCTID_FLD + "," + MST_TransactionHistoryTable.STOCKUMID_FLD + "," + MST_TransactionHistoryTable.CURRENCYID_FLD + "," + MST_TransactionHistoryTable.QUANTITY_FLD + "," + MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.BINOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.MASLOCCOMMITQUANTITY_FLD + "," + MST_TransactionHistoryTable.LOCATIONCOMMITQUANTITY_FLD + "," + MST_TransactionHistoryTable.BINCOMMITQUANTITY_FLD + "," + MST_TransactionHistoryTable.COMMENT_FLD + "," + MST_TransactionHistoryTable.EXCHANGERATE_FLD + "," + MST_TransactionHistoryTable.LOT_FLD + "," + MST_TransactionHistoryTable.SERIAL_FLD + "," + MST_TransactionHistoryTable.OLDAVGCOST_FLD + "," + MST_TransactionHistoryTable.ISSUEPUROSEID_FLD + "," + MST_TransactionHistoryTable.USERNAME_FLD + "," + MST_TransactionHistoryTable.NEWAVGCOST_FLD + ")" + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); if (objObject.MasterLocationID > 0) ocmdPCS.Parameters[MST_TransactionHistoryTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; else ocmdPCS.Parameters[MST_TransactionHistoryTable.MASTERLOCATIONID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.BINID_FLD, OleDbType.Integer)); if (objObject.BinID > 0) ocmdPCS.Parameters[MST_TransactionHistoryTable.BINID_FLD].Value = objObject.BinID; else ocmdPCS.Parameters[MST_TransactionHistoryTable.BINID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.BUYSELLCOST_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.BUYSELLCOST_FLD].Value = objObject.BuySellCost; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.INSPSTATUS_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.INSPSTATUS_FLD].Value = objObject.InspStatus; //ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.TRANSACTIONHISTORYID_FLD, OleDbType.Integer)); //ocmdPCS.Parameters[MST_TransactionHistoryTable.TRANSACTIONHISTORYID_FLD].Value = objObject.TransactionHistoryID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.TRANSDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[MST_TransactionHistoryTable.TRANSDATE_FLD].Value = objObject.TransDate; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.POSTDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[MST_TransactionHistoryTable.POSTDATE_FLD].Value = objObject.PostDate; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.REFMASTERID_FLD, OleDbType.Integer)); if (objObject.RefMasterID > 0) ocmdPCS.Parameters[MST_TransactionHistoryTable.REFMASTERID_FLD].Value = objObject.RefMasterID; else ocmdPCS.Parameters[MST_TransactionHistoryTable.REFMASTERID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.REFDETAILID_FLD, OleDbType.Integer)); if (objObject.RefDetailID > 0) ocmdPCS.Parameters[MST_TransactionHistoryTable.REFDETAILID_FLD].Value = objObject.RefDetailID; else ocmdPCS.Parameters[MST_TransactionHistoryTable.REFDETAILID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.COST_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.COST_FLD].Value = objObject.Cost; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.TRANTYPEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.TRANTYPEID_FLD].Value = objObject.TranTypeID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.PARTYID_FLD, OleDbType.Integer)); if (objObject.PartyID > 0) ocmdPCS.Parameters[MST_TransactionHistoryTable.PARTYID_FLD].Value = objObject.PartyID; else ocmdPCS.Parameters[MST_TransactionHistoryTable.PARTYID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.PARTYLOCATIONID_FLD, OleDbType.Integer)); if (objObject.PartyLocationID > 0) ocmdPCS.Parameters[MST_TransactionHistoryTable.PARTYLOCATIONID_FLD].Value = objObject.PartyLocationID; else ocmdPCS.Parameters[MST_TransactionHistoryTable.PARTYLOCATIONID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.LOCATIONID_FLD, OleDbType.Integer)); if (objObject.LocationID > 0) ocmdPCS.Parameters[MST_TransactionHistoryTable.LOCATIONID_FLD].Value = objObject.LocationID; else ocmdPCS.Parameters[MST_TransactionHistoryTable.LOCATIONID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.PRODUCTID_FLD, OleDbType.Integer)); if (objObject.ProductID > 0) ocmdPCS.Parameters[MST_TransactionHistoryTable.PRODUCTID_FLD].Value = objObject.ProductID; else ocmdPCS.Parameters[MST_TransactionHistoryTable.PRODUCTID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.STOCKUMID_FLD, OleDbType.Integer)); if (objObject.StockUMID > 0) ocmdPCS.Parameters[MST_TransactionHistoryTable.STOCKUMID_FLD].Value = objObject.StockUMID; else ocmdPCS.Parameters[MST_TransactionHistoryTable.STOCKUMID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.CURRENCYID_FLD, OleDbType.Integer)); if (objObject.CurrencyID > 0) ocmdPCS.Parameters[MST_TransactionHistoryTable.CURRENCYID_FLD].Value = objObject.CurrencyID; else ocmdPCS.Parameters[MST_TransactionHistoryTable.CURRENCYID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.QUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.QUANTITY_FLD].Value = objObject.Quantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD].Value = objObject.MasLocOHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD].Value = objObject.LocationOHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.BINOHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.BINOHQUANTITY_FLD].Value = objObject.BinOHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.MASLOCCOMMITQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.MASLOCCOMMITQUANTITY_FLD].Value = objObject.MasLocCommitQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.LOCATIONCOMMITQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.LOCATIONCOMMITQUANTITY_FLD].Value = objObject.LocationCommitQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.BINCOMMITQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.BINCOMMITQUANTITY_FLD].Value = objObject.BinCommitQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.COMMENT_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_TransactionHistoryTable.COMMENT_FLD].Value = objObject.Comment; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.EXCHANGERATE_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.EXCHANGERATE_FLD].Value = objObject.ExchangeRate; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.LOT_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_TransactionHistoryTable.LOT_FLD].Value = objObject.Lot; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.SERIAL_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_TransactionHistoryTable.SERIAL_FLD].Value = objObject.Serial; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.OLDAVGCOST_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.OLDAVGCOST_FLD].Value = objObject.OldAvgCost; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.ISSUEPUROSEID_FLD, OleDbType.Integer)); if (objObject.PurposeID > 0) ocmdPCS.Parameters[MST_TransactionHistoryTable.ISSUEPUROSEID_FLD].Value = objObject.PurposeID; else ocmdPCS.Parameters[MST_TransactionHistoryTable.ISSUEPUROSEID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.USERNAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_TransactionHistoryTable.USERNAME_FLD].Value = objObject.Username; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.NEWAVGCOST_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.NEWAVGCOST_FLD].Value = objObject.NewAvgCost; ocmdPCS.CommandText = strSql; ocmdPCS.CommandTimeout = 10000; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to MST_TransactionHistory /// </summary> /// <Inputs> /// MST_TransactionHistoryVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Thursday, June 30, 2005 /// </History> public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql = "DELETE " + MST_TransactionHistoryTable.TABLE_NAME + " WHERE " + "MasterLocationID" + "=" + pintID.ToString(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to MST_TransactionHistory /// </summary> /// <Inputs> /// MST_TransactionHistoryVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Thursday, June 30, 2005 /// </History> public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; //DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + MST_TransactionHistoryTable.MASTERLOCATIONID_FLD + "," + MST_TransactionHistoryTable.BINID_FLD + "," + MST_TransactionHistoryTable.BUYSELLCOST_FLD + "," + MST_TransactionHistoryTable.INSPSTATUS_FLD + "," + MST_TransactionHistoryTable.TRANSACTIONHISTORYID_FLD + "," + MST_TransactionHistoryTable.TRANSDATE_FLD + "," + MST_TransactionHistoryTable.POSTDATE_FLD + "," + MST_TransactionHistoryTable.REFMASTERID_FLD + "," + MST_TransactionHistoryTable.REFDETAILID_FLD + "," + MST_TransactionHistoryTable.COST_FLD + "," + MST_TransactionHistoryTable.CCNID_FLD + "," + MST_TransactionHistoryTable.TRANTYPEID_FLD + "," + MST_TransactionHistoryTable.PARTYID_FLD + "," + MST_TransactionHistoryTable.PARTYLOCATIONID_FLD + "," + MST_TransactionHistoryTable.LOCATIONID_FLD + "," + MST_TransactionHistoryTable.PRODUCTID_FLD + "," + MST_TransactionHistoryTable.STOCKUMID_FLD + "," + MST_TransactionHistoryTable.CURRENCYID_FLD + "," + MST_TransactionHistoryTable.QUANTITY_FLD + "," + MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.BINOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.MASLOCCOMMITQUANTITY_FLD + "," + MST_TransactionHistoryTable.LOCATIONCOMMITQUANTITY_FLD + "," + MST_TransactionHistoryTable.BINCOMMITQUANTITY_FLD + "," + MST_TransactionHistoryTable.COMMENT_FLD + "," + MST_TransactionHistoryTable.EXCHANGERATE_FLD + "," + MST_TransactionHistoryTable.LOT_FLD + "," + MST_TransactionHistoryTable.SERIAL_FLD + "," + MST_TransactionHistoryTable.OLDAVGCOST_FLD + "," + MST_TransactionHistoryTable.USERNAME_FLD + "," + MST_TransactionHistoryTable.NEWAVGCOST_FLD + " FROM " + MST_TransactionHistoryTable.TABLE_NAME + " WHERE " + MST_TransactionHistoryTable.MASTERLOCATIONID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); MST_TransactionHistoryVO objObject = new MST_TransactionHistoryVO(); while (odrPCS.Read()) { objObject.MasterLocationID = int.Parse(odrPCS[MST_TransactionHistoryTable.MASTERLOCATIONID_FLD].ToString().Trim()); objObject.BinID = int.Parse(odrPCS[MST_TransactionHistoryTable.BINID_FLD].ToString().Trim()); objObject.BuySellCost = Decimal.Parse(odrPCS[MST_TransactionHistoryTable.BUYSELLCOST_FLD].ToString().Trim()); objObject.InspStatus = int.Parse(odrPCS[MST_TransactionHistoryTable.INSPSTATUS_FLD].ToString().Trim()); objObject.TransactionHistoryID = int.Parse(odrPCS[MST_TransactionHistoryTable.TRANSACTIONHISTORYID_FLD].ToString().Trim()); objObject.TransDate = DateTime.Parse(odrPCS[MST_TransactionHistoryTable.TRANSDATE_FLD].ToString().Trim()); objObject.PostDate = DateTime.Parse(odrPCS[MST_TransactionHistoryTable.POSTDATE_FLD].ToString().Trim()); objObject.RefMasterID = int.Parse(odrPCS[MST_TransactionHistoryTable.REFMASTERID_FLD].ToString().Trim()); objObject.RefDetailID = int.Parse(odrPCS[MST_TransactionHistoryTable.REFDETAILID_FLD].ToString().Trim()); objObject.Cost = Decimal.Parse(odrPCS[MST_TransactionHistoryTable.COST_FLD].ToString().Trim()); objObject.CCNID = int.Parse(odrPCS[MST_TransactionHistoryTable.CCNID_FLD].ToString().Trim()); objObject.TranTypeID = int.Parse(odrPCS[MST_TransactionHistoryTable.TRANTYPEID_FLD].ToString().Trim()); objObject.PartyID = int.Parse(odrPCS[MST_TransactionHistoryTable.PARTYID_FLD].ToString().Trim()); objObject.PartyLocationID = int.Parse(odrPCS[MST_TransactionHistoryTable.PARTYLOCATIONID_FLD].ToString().Trim()); objObject.LocationID = int.Parse(odrPCS[MST_TransactionHistoryTable.LOCATIONID_FLD].ToString().Trim()); objObject.ProductID = int.Parse(odrPCS[MST_TransactionHistoryTable.PRODUCTID_FLD].ToString().Trim()); objObject.StockUMID = int.Parse(odrPCS[MST_TransactionHistoryTable.STOCKUMID_FLD].ToString().Trim()); objObject.CurrencyID = int.Parse(odrPCS[MST_TransactionHistoryTable.CURRENCYID_FLD].ToString().Trim()); objObject.Quantity = Decimal.Parse(odrPCS[MST_TransactionHistoryTable.QUANTITY_FLD].ToString().Trim()); objObject.MasLocOHQuantity = Decimal.Parse(odrPCS[MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD].ToString().Trim()); objObject.LocationOHQuantity = Decimal.Parse(odrPCS[MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD].ToString().Trim()); objObject.BinOHQuantity = Decimal.Parse(odrPCS[MST_TransactionHistoryTable.BINOHQUANTITY_FLD].ToString().Trim()); objObject.MasLocCommitQuantity = Decimal.Parse(odrPCS[MST_TransactionHistoryTable.MASLOCCOMMITQUANTITY_FLD].ToString().Trim()); objObject.LocationCommitQuantity = Decimal.Parse(odrPCS[MST_TransactionHistoryTable.LOCATIONCOMMITQUANTITY_FLD].ToString().Trim()); objObject.BinCommitQuantity = Decimal.Parse(odrPCS[MST_TransactionHistoryTable.BINCOMMITQUANTITY_FLD].ToString().Trim()); objObject.Comment = odrPCS[MST_TransactionHistoryTable.COMMENT_FLD].ToString().Trim(); objObject.ExchangeRate = Decimal.Parse(odrPCS[MST_TransactionHistoryTable.EXCHANGERATE_FLD].ToString().Trim()); objObject.Lot = odrPCS[MST_TransactionHistoryTable.LOT_FLD].ToString().Trim(); objObject.Serial = odrPCS[MST_TransactionHistoryTable.SERIAL_FLD].ToString().Trim(); objObject.OldAvgCost = Decimal.Parse(odrPCS[MST_TransactionHistoryTable.OLDAVGCOST_FLD].ToString().Trim()); objObject.NewAvgCost = Decimal.Parse(odrPCS[MST_TransactionHistoryTable.NEWAVGCOST_FLD].ToString().Trim()); objObject.Username = odrPCS[MST_TransactionHistoryTable.USERNAME_FLD].ToString().Trim(); } return objObject; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to MST_TransactionHistory /// </summary> /// <Inputs> /// MST_TransactionHistoryVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Thursday, June 30, 2005 /// </History> public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; MST_TransactionHistoryVO objObject = (MST_TransactionHistoryVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql = "UPDATE MST_TransactionHistory SET " + MST_TransactionHistoryTable.BINID_FLD + "= ?" + "," + MST_TransactionHistoryTable.BUYSELLCOST_FLD + "= ?" + "," + MST_TransactionHistoryTable.INSPSTATUS_FLD + "= ?" + "," + MST_TransactionHistoryTable.TRANSACTIONHISTORYID_FLD + "= ?" + "," + MST_TransactionHistoryTable.TRANSDATE_FLD + "= ?" + "," + MST_TransactionHistoryTable.POSTDATE_FLD + "= ?" + "," + MST_TransactionHistoryTable.REFMASTERID_FLD + "= ?" + "," + MST_TransactionHistoryTable.REFDETAILID_FLD + "= ?" + "," + MST_TransactionHistoryTable.COST_FLD + "= ?" + "," + MST_TransactionHistoryTable.CCNID_FLD + "= ?" + "," + MST_TransactionHistoryTable.TRANTYPEID_FLD + "= ?" + "," + MST_TransactionHistoryTable.PARTYID_FLD + "= ?" + "," + MST_TransactionHistoryTable.PARTYLOCATIONID_FLD + "= ?" + "," + MST_TransactionHistoryTable.LOCATIONID_FLD + "= ?" + "," + MST_TransactionHistoryTable.PRODUCTID_FLD + "= ?" + "," + MST_TransactionHistoryTable.STOCKUMID_FLD + "= ?" + "," + MST_TransactionHistoryTable.CURRENCYID_FLD + "= ?" + "," + MST_TransactionHistoryTable.QUANTITY_FLD + "= ?" + "," + MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD + "= ?" + "," + MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD + "= ?" + "," + MST_TransactionHistoryTable.BINOHQUANTITY_FLD + "= ?" + "," + MST_TransactionHistoryTable.COMMENT_FLD + "= ?" + "," + MST_TransactionHistoryTable.EXCHANGERATE_FLD + "= ?" + "," + MST_TransactionHistoryTable.LOT_FLD + "= ?" + "," + MST_TransactionHistoryTable.SERIAL_FLD + "= ?" + "," + MST_TransactionHistoryTable.OLDAVGCOST_FLD + "= ?" + "," + MST_TransactionHistoryTable.NEWAVGCOST_FLD + "= ?" + " WHERE " + MST_TransactionHistoryTable.MASTERLOCATIONID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.BINID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.BINID_FLD].Value = objObject.BinID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.BUYSELLCOST_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.BUYSELLCOST_FLD].Value = objObject.BuySellCost; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.INSPSTATUS_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.INSPSTATUS_FLD].Value = objObject.InspStatus; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.TRANSACTIONHISTORYID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.TRANSACTIONHISTORYID_FLD].Value = objObject.TransactionHistoryID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.TRANSDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[MST_TransactionHistoryTable.TRANSDATE_FLD].Value = objObject.TransDate; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.POSTDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[MST_TransactionHistoryTable.POSTDATE_FLD].Value = objObject.PostDate; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.REFMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.REFMASTERID_FLD].Value = objObject.RefMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.REFDETAILID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.REFDETAILID_FLD].Value = objObject.RefDetailID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.COST_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.COST_FLD].Value = objObject.Cost; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.TRANTYPEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.TRANTYPEID_FLD].Value = objObject.TranTypeID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.PARTYID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.PARTYID_FLD].Value = objObject.PartyID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.PARTYLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.PARTYLOCATIONID_FLD].Value = objObject.PartyLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.LOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.LOCATIONID_FLD].Value = objObject.LocationID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.STOCKUMID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.STOCKUMID_FLD].Value = objObject.StockUMID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.CURRENCYID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.CURRENCYID_FLD].Value = objObject.CurrencyID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.QUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.QUANTITY_FLD].Value = objObject.Quantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD].Value = objObject.MasLocOHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD].Value = objObject.LocationOHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.BINOHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.BINOHQUANTITY_FLD].Value = objObject.BinOHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.COMMENT_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_TransactionHistoryTable.COMMENT_FLD].Value = objObject.Comment; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.EXCHANGERATE_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.EXCHANGERATE_FLD].Value = objObject.ExchangeRate; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.LOT_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_TransactionHistoryTable.LOT_FLD].Value = objObject.Lot; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.SERIAL_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_TransactionHistoryTable.SERIAL_FLD].Value = objObject.Serial; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.OLDAVGCOST_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.OLDAVGCOST_FLD].Value = objObject.OldAvgCost; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.NEWAVGCOST_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.NEWAVGCOST_FLD].Value = objObject.NewAvgCost; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to MST_TransactionHistory /// </summary> /// <Inputs> /// MST_TransactionHistoryVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Thursday, June 30, 2005 /// </History> public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + MST_TransactionHistoryTable.MASTERLOCATIONID_FLD + "," + MST_TransactionHistoryTable.BINID_FLD + "," + MST_TransactionHistoryTable.BUYSELLCOST_FLD + "," + MST_TransactionHistoryTable.INSPSTATUS_FLD + "," + MST_TransactionHistoryTable.TRANSACTIONHISTORYID_FLD + "," + MST_TransactionHistoryTable.TRANSDATE_FLD + "," + MST_TransactionHistoryTable.POSTDATE_FLD + "," + MST_TransactionHistoryTable.REFMASTERID_FLD + "," + MST_TransactionHistoryTable.REFDETAILID_FLD + "," + MST_TransactionHistoryTable.COST_FLD + "," + MST_TransactionHistoryTable.CCNID_FLD + "," + MST_TransactionHistoryTable.TRANTYPEID_FLD + "," + MST_TransactionHistoryTable.PARTYID_FLD + "," + MST_TransactionHistoryTable.PARTYLOCATIONID_FLD + "," + MST_TransactionHistoryTable.LOCATIONID_FLD + "," + MST_TransactionHistoryTable.PRODUCTID_FLD + "," + MST_TransactionHistoryTable.STOCKUMID_FLD + "," + MST_TransactionHistoryTable.CURRENCYID_FLD + "," + MST_TransactionHistoryTable.QUANTITY_FLD + "," + MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.BINOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.MASLOCCOMMITQUANTITY_FLD + "," + MST_TransactionHistoryTable.LOCATIONCOMMITQUANTITY_FLD + "," + MST_TransactionHistoryTable.BINCOMMITQUANTITY_FLD + "," + MST_TransactionHistoryTable.COMMENT_FLD + "," + MST_TransactionHistoryTable.EXCHANGERATE_FLD + "," + MST_TransactionHistoryTable.LOT_FLD + "," + MST_TransactionHistoryTable.SERIAL_FLD + "," + MST_TransactionHistoryTable.OLDAVGCOST_FLD + "," + MST_TransactionHistoryTable.USERNAME_FLD + "," + MST_TransactionHistoryTable.NEWAVGCOST_FLD + " FROM " + MST_TransactionHistoryTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, MST_TransactionHistoryTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataSet List(int pintID) { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + MST_TransactionHistoryTable.MASTERLOCATIONID_FLD + "," + MST_TransactionHistoryTable.BINID_FLD + "," + MST_TransactionHistoryTable.BUYSELLCOST_FLD + "," + MST_TransactionHistoryTable.INSPSTATUS_FLD + "," + MST_TransactionHistoryTable.TRANSACTIONHISTORYID_FLD + "," + MST_TransactionHistoryTable.TRANSDATE_FLD + "," + MST_TransactionHistoryTable.POSTDATE_FLD + "," + MST_TransactionHistoryTable.REFMASTERID_FLD + "," + MST_TransactionHistoryTable.REFDETAILID_FLD + "," + MST_TransactionHistoryTable.COST_FLD + "," + MST_TransactionHistoryTable.CCNID_FLD + "," + MST_TransactionHistoryTable.TRANTYPEID_FLD + "," + MST_TransactionHistoryTable.PARTYID_FLD + "," + MST_TransactionHistoryTable.PARTYLOCATIONID_FLD + "," + MST_TransactionHistoryTable.LOCATIONID_FLD + "," + MST_TransactionHistoryTable.PRODUCTID_FLD + "," + MST_TransactionHistoryTable.STOCKUMID_FLD + "," + MST_TransactionHistoryTable.CURRENCYID_FLD + "," + MST_TransactionHistoryTable.QUANTITY_FLD + "," + MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.BINOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.MASLOCCOMMITQUANTITY_FLD + "," + MST_TransactionHistoryTable.LOCATIONCOMMITQUANTITY_FLD + "," + MST_TransactionHistoryTable.BINCOMMITQUANTITY_FLD + "," + MST_TransactionHistoryTable.COMMENT_FLD + "," + MST_TransactionHistoryTable.EXCHANGERATE_FLD + "," + MST_TransactionHistoryTable.LOT_FLD + "," + MST_TransactionHistoryTable.SERIAL_FLD + "," + MST_TransactionHistoryTable.OLDAVGCOST_FLD + "," + MST_TransactionHistoryTable.USERNAME_FLD + "," + MST_TransactionHistoryTable.NEWAVGCOST_FLD + " FROM " + MST_TransactionHistoryTable.TABLE_NAME + " WHERE " + MST_TransactionHistoryTable.TRANSACTIONHISTORYID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, MST_TransactionHistoryTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataTable GetSchema() { const string METHOD_NAME = THIS + ".GetSchema()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT TOP 0 * FROM MST_TransactionHistory"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); DataTable dtbData = new DataTable(MST_TransactionHistoryTable.TABLE_NAME); odadPCS.Fill(dtbData); return dtbData; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to MST_TransactionHistory /// </summary> /// <Inputs> /// MST_TransactionHistoryVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Thursday, June 30, 2005 /// </History> public void UpdateDataSet(DataSet pdstData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS = null; OleDbCommandBuilder odcbPCS; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql = "SELECT " + MST_TransactionHistoryTable.MASTERLOCATIONID_FLD + "," + MST_TransactionHistoryTable.BINID_FLD + "," + MST_TransactionHistoryTable.BUYSELLCOST_FLD + "," + MST_TransactionHistoryTable.INSPSTATUS_FLD + "," + MST_TransactionHistoryTable.TRANSACTIONHISTORYID_FLD + "," + MST_TransactionHistoryTable.TRANSDATE_FLD + "," + MST_TransactionHistoryTable.POSTDATE_FLD + "," + MST_TransactionHistoryTable.REFMASTERID_FLD + "," + MST_TransactionHistoryTable.REFDETAILID_FLD + "," + MST_TransactionHistoryTable.COST_FLD + "," + MST_TransactionHistoryTable.CCNID_FLD + "," + MST_TransactionHistoryTable.TRANTYPEID_FLD + "," + MST_TransactionHistoryTable.PARTYID_FLD + "," + MST_TransactionHistoryTable.PARTYLOCATIONID_FLD + "," + MST_TransactionHistoryTable.LOCATIONID_FLD + "," + MST_TransactionHistoryTable.PRODUCTID_FLD + "," + MST_TransactionHistoryTable.STOCKUMID_FLD + "," + MST_TransactionHistoryTable.CURRENCYID_FLD + "," + MST_TransactionHistoryTable.QUANTITY_FLD + "," + MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.BINOHQUANTITY_FLD + "," + MST_TransactionHistoryTable.COMMENT_FLD + "," + MST_TransactionHistoryTable.EXCHANGERATE_FLD + "," + MST_TransactionHistoryTable.LOT_FLD + "," + MST_TransactionHistoryTable.SERIAL_FLD + "," + MST_TransactionHistoryTable.OLDAVGCOST_FLD + "," + MST_TransactionHistoryTable.USERNAME_FLD + "," + MST_TransactionHistoryTable.NEWAVGCOST_FLD + " FROM " + MST_TransactionHistoryTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); OleDbCommand cmdSelect = new OleDbCommand(strSql, oconPCS); cmdSelect.CommandTimeout = 10000; odadPCS.SelectCommand = cmdSelect; odcbPCS = new OleDbCommandBuilder(odadPCS); pdstData.EnforceConstraints = false; odadPCS.Update(pdstData, MST_TransactionHistoryTable.TABLE_NAME); } catch (OleDbException ex) { if (ex.Errors.Count > 0) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Gets in quantity in period of time /// </summary> /// <param name="pintCCNID">CCN</param> /// <param name="pdtmFromDate">From Date</param> /// <param name="pdtmToDate">To Date</param> /// <returns>DataTable</returns> public DataTable GetInQuantity(int pintCCNID, DateTime pdtmFromDate, DateTime pdtmToDate) { OleDbConnection oconPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); string strSql = "SELECT SUM(ISNULL(Quantity,0)) AS " + MST_TransactionHistoryTable.QUANTITY_FLD + ", ProductID FROM MST_TransactionHistory" + " JOIN MST_TranType ON MST_TransactionHistory.TranTypeID = MST_TranType.TranTypeID" + " WHERE Type IN ( " + (int) TransactionHistoryType.In + "," + (int) TransactionHistoryType.Both + ")" + " AND CCNID = " + pintCCNID + " AND TransDate >= ? AND TransDate <= ?" + " GROUP BY ProductID"; OleDbCommand cmdPCS = new OleDbCommand(strSql, oconPCS); cmdPCS.Parameters.Add(new OleDbParameter("FromDate", OleDbType.Date)).Value = pdtmFromDate; cmdPCS.Parameters.Add(new OleDbParameter("ToDate", OleDbType.Date)).Value = pdtmToDate; cmdPCS.Connection.Open(); DataTable dtbData = new DataTable(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(cmdPCS); odadPCS.Fill(dtbData); return dtbData; } finally { if (oconPCS != null) if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); } } /// <summary> /// Gets out quantity in period of time /// </summary> /// <param name="pintCCNID">CCN</param> /// <param name="pdtmFromDate">From Date</param> /// <param name="pdtmToDate">To Date</param> /// <returns>DataTable</returns> public DataTable GetOutQuantity(int pintCCNID, DateTime pdtmFromDate, DateTime pdtmToDate) { OleDbConnection oconPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); string strSql = "SELECT SUM(ISNULL(Quantity,0)) AS " + MST_TransactionHistoryTable.QUANTITY_FLD + ", ProductID FROM MST_TransactionHistory" + " JOIN MST_TranType ON MST_TransactionHistory.TranTypeID = MST_TranType.TranTypeID" + " WHERE Type = " + (int) TransactionHistoryType.Out + " AND CCNID = " + pintCCNID + " AND TransDate >= ? AND TransDate <= ?" + " GROUP BY ProductID"; OleDbCommand cmdPCS = new OleDbCommand(strSql, oconPCS); cmdPCS.Parameters.Add(new OleDbParameter("FromDate", OleDbType.Date)).Value = pdtmFromDate; cmdPCS.Parameters.Add(new OleDbParameter("ToDate", OleDbType.Date)).Value = pdtmToDate; cmdPCS.Connection.Open(); DataTable dtbData = new DataTable(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(cmdPCS); odadPCS.Fill(dtbData); return dtbData; } finally { if (oconPCS != null) if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); } } public DataSet RetrieveCacheData(int pintMasterLocationID, string pstrLocationID, string pstrBinID, string pstrProductID) { OleDbConnection oconPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); string strSql = "SELECT MasterLocationID, ProductID, OHQuantity, CommitQuantity" + " FROM IV_MasLocCache WHERE MasterLocationID IN (" + pintMasterLocationID + ")" + " AND ProductID IN (" + pstrProductID + ");" + " SELECT LocationID, ProductID, OHQuantity, CommitQuantity" + " FROM IV_LocationCache" + " WHERE LocationID IN (" + pstrLocationID + ")" + " AND ProductID IN (" + pstrProductID + ");" + " SELECT BinID, ProductID, OHQuantity, CommitQuantity" + " FROM IV_BinCache" + " WHERE BinID IN (" + pstrBinID + ")" + " AND ProductID IN (" + pstrProductID + ");"; OleDbCommand cmdPCS = new OleDbCommand(strSql, oconPCS); cmdPCS.Connection.Open(); DataSet dstData = new DataSet(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(cmdPCS); odadPCS.Fill(dstData); return dstData; } finally { if (oconPCS != null) if (oconPCS.State != ConnectionState.Closed) oconPCS.Close(); } } public void UpdatebyRefMasterID(object pobjObjecVO) { const string METHOD_NAME = THIS + ".UpdatebyRefMasterID()"; MST_TransactionHistoryVO objObject = (MST_TransactionHistoryVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql = "UPDATE MST_TransactionHistory SET " + MST_TransactionHistoryTable.BINID_FLD + "= ?" + "," + MST_TransactionHistoryTable.CCNID_FLD + "= ?" + "," + MST_TransactionHistoryTable.TRANTYPEID_FLD + "= ?" + "," + MST_TransactionHistoryTable.LOCATIONID_FLD + "= ?" + "," + MST_TransactionHistoryTable.PRODUCTID_FLD + "= ?" + "," + MST_TransactionHistoryTable.QUANTITY_FLD + "= ?" + "," + MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD + "= ?" + "," + MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD + "= ?" + "," + MST_TransactionHistoryTable.BINOHQUANTITY_FLD + "= ?" + "," + MST_TransactionHistoryTable.OLDAVGCOST_FLD + "= ?" + "," + MST_TransactionHistoryTable.NEWAVGCOST_FLD + "= ?" + " WHERE " + MST_TransactionHistoryTable.REFMASTERID_FLD + "= ?" + " AND " + MST_TransactionHistoryTable.PRODUCTID_FLD + "= ?" + " AND " + MST_TransactionHistoryTable.TRANTYPEID_FLD + "= ?" ; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.BINID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.BINID_FLD].Value = objObject.BinID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.TRANTYPEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.TRANTYPEID_FLD].Value = objObject.TranTypeID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.LOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.LOCATIONID_FLD].Value = objObject.LocationID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.QUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.QUANTITY_FLD].Value = objObject.Quantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD].Value = objObject.MasLocOHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD].Value = objObject.LocationOHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.BINOHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.BINOHQUANTITY_FLD].Value = objObject.BinOHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.OLDAVGCOST_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.OLDAVGCOST_FLD].Value = objObject.OldAvgCost; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.NEWAVGCOST_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[MST_TransactionHistoryTable.NEWAVGCOST_FLD].Value = objObject.NewAvgCost; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.REFMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.REFMASTERID_FLD].Value = objObject.RefMasterID; ocmdPCS.Parameters.Add(new OleDbParameter("PRODUCTID_FLD", OleDbType.Integer)).Value = objObject.ProductID; //ocmdPCS.Parameters[MST_TransactionHistoryTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter("TRANTYPEID_FLD", OleDbType.Integer)).Value = objObject.TranTypeID; //ocmdPCS.Parameters[MST_TransactionHistoryTable.TRANTYPEID_FLD].Value = objObject.TranTypeID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public int GetTransactionHistoryID(int refMasterId, int refDetailId) { const string METHOD_NAME = THIS + ".GetTransactionHistoryID()"; OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "Select TransactionHistoryId " + "FROM MST_TransactionHistory "+ "Where refmasterid = " + refMasterId.ToString().Trim() + " and Refdetailid = "+ refDetailId.ToString().Trim(); Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); int intTransactionHistoryID = 0; while (odrPCS.Read()) { intTransactionHistoryID = int.Parse(odrPCS[MST_TransactionHistoryTable.TRANSACTIONHISTORYID_FLD].ToString().Trim()); } return intTransactionHistoryID; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void DeleteByRefMaster(int printRefMasterID, int printRefDetailID) { const string METHOD_NAME = THIS + ".DeleteByRefMaster()"; string strSql = String.Empty; strSql = "DELETE " + MST_TransactionHistoryTable.TABLE_NAME + " WHERE " + MST_TransactionHistoryTable.REFMASTERID_FLD + "=" + printRefMasterID.ToString() +" AND "+ MST_TransactionHistoryTable.REFDETAILID_FLD + " = " + printRefDetailID.ToString(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void UpdateTranType(int refPurchaseMaster, int oldTranTypeID, int tranTypeId, int inspStatus) { const string METHOD_NAME = THIS + ".UpdateTranType()"; //prepare value for parameters OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql = "UPDATE MST_TransactionHistory SET " + MST_TransactionHistoryTable.TRANTYPEID_FLD + "= ?" + "," + MST_TransactionHistoryTable.INSPSTATUS_FLD + "= ?" + " WHERE " + MST_TransactionHistoryTable.REFMASTERID_FLD + "= ?" + " AND " + MST_TransactionHistoryTable.TRANTYPEID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.TRANTYPEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.TRANTYPEID_FLD].Value = tranTypeId; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.INSPSTATUS_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.INSPSTATUS_FLD].Value = inspStatus; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.REFMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_TransactionHistoryTable.REFMASTERID_FLD].Value = refPurchaseMaster; ocmdPCS.Parameters.Add(new OleDbParameter("OldTranTypeID", OleDbType.Integer)).Value = oldTranTypeID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Update transaction type for detail information /// </summary> /// <param name="pintRefMasterID">Reference transaction master id</param> /// <param name="pintRefDetailID">Reference transaction detail id</param> /// <param name="oldTranTypeID">Old transaction type</param> /// <param name="newTranTypeID">New transaction type</param> /// <param name="inspStatus">Inspection status</param> public void UpdateTranType(int pintRefMasterID, int pintRefDetailID, int oldTranTypeID, int newTranTypeID, int inspStatus) { const string METHOD_NAME = THIS + ".UpdateTranType()"; //prepare value for parameters OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql = "UPDATE MST_TransactionHistory SET " + MST_TransactionHistoryTable.TRANTYPEID_FLD + "= ?" + "," + MST_TransactionHistoryTable.INSPSTATUS_FLD + "= ?" + " WHERE " + MST_TransactionHistoryTable.REFMASTERID_FLD + "= ?" + " AND " + MST_TransactionHistoryTable.REFDETAILID_FLD + "= ?" + " AND " + MST_TransactionHistoryTable.TRANTYPEID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.TRANTYPEID_FLD, OleDbType.Integer)).Value = newTranTypeID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.INSPSTATUS_FLD, OleDbType.Integer)).Value = inspStatus; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.REFMASTERID_FLD, OleDbType.Integer)).Value = pintRefMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(MST_TransactionHistoryTable.REFDETAILID_FLD, OleDbType.Integer)).Value = pintRefDetailID; ocmdPCS.Parameters.Add(new OleDbParameter("OldTranTypeID", OleDbType.Integer)).Value = oldTranTypeID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataTable ListForUpdateStockTaking(DateTime pdtmStockTakingDate) { const string METHOD_NAME = THIS + ".ListForUpdateStockTaking()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { DateTime dtmEndDate = new DateTime(pdtmStockTakingDate.Year, pdtmStockTakingDate.Month, pdtmStockTakingDate.Day, 23, 59, 59); string strSql = "SELECT MST_TranType.TranTypeID, MST_TranType.Code TranType, LocationID, BinID, ProductID, PostDate," + " CASE MST_TranType.Type WHEN 0 THEN -Quantity ELSE Quantity END AS Quantity" + " FROM MST_TransactionHistory JOIN MST_TranType ON MST_TransactionHistory.TranTypeID = MST_TranType.TranTypeID" + " AND MST_TranType.Type IN (" + (int)TransactionHistoryType.In + "," + (int)TransactionHistoryType.Out + "," + (int)TransactionHistoryType.Both + ")" + " WHERE PostDate BETWEEN ? AND ?" + " AND Quantity <> 0" + " ORDER BY MST_TranType.TranTypeID, LocationID, BinID, ProductID, PostDate"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add("FromDate", OleDbType.Date).Value = pdtmStockTakingDate; ocmdPCS.Parameters.Add("ToDate", OleDbType.Date).Value = dtmEndDate; ocmdPCS.Connection.Open(); DataTable dtbData = new DataTable(MST_TransactionHistoryTable.TABLE_NAME); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbData); return dtbData; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using Microsoft.Data.SqlClient; using System.Threading.Tasks; namespace Artisan.Orm { public class RepositoryBase: IDisposable { public SqlConnection Connection { get; private set; } public string ConnectionString { get; private set; } public SqlTransaction Transaction { get; set; } public RepositoryBase() { ConnectionString = ConnectionStringHelper.GetConnectionString(); Connection = new SqlConnection(ConnectionString); Transaction = null; } public RepositoryBase(string connectionString, string activeSolutionConfiguration = null) : this(null, connectionString, activeSolutionConfiguration) {} public RepositoryBase(SqlTransaction transaction, string connectionString, string activeSolutionConfiguration = null) { if (connectionString.Contains(";") && connectionString.Contains("=")) ConnectionString = connectionString; else ConnectionString = ConnectionStringHelper.GetConnectionString(connectionString, activeSolutionConfiguration); Connection = new SqlConnection(ConnectionString); Transaction = transaction; } public void BeginTransaction(IsolationLevel isolationLevel, Action<SqlTransaction> action) { var isConnectionClosed = Connection.State == ConnectionState.Closed; if (isConnectionClosed) Connection.Open(); Transaction = Connection.BeginTransaction(isolationLevel); try { action(Transaction); } catch { Transaction.Rollback(); throw; } finally { Transaction?.Dispose(); Transaction = null; if(isConnectionClosed) Connection.Close(); } } public void BeginTransaction(Action<SqlTransaction> action) { BeginTransaction(IsolationLevel.Unspecified, action); } public SqlCommand CreateCommand() { var cmd = Connection.CreateCommand(); if (Transaction != null) cmd.Transaction = Transaction; return cmd; } public SqlCommand CreateCommand(string sql, params SqlParameter[] sqlParameters) { var cmd = CreateCommand(); cmd.ConfigureCommand(sql, sqlParameters); return cmd; } public SqlCommand CreateCommand(string sql, Action<SqlCommand> action) { var cmd = CreateCommand(); cmd.ConfigureCommand(sql, action); return cmd; } /// <summary> /// <para/>Prepares SqlCommand and pass it to a Func-parameter. /// <para/>Parameter "func" is the code where SqlCommand has to be configured with parameters, execute reader and return result. /// </summary> public T GetByCommand<T>(Func<SqlCommand, T> func) { using (var cmd = CreateCommand()) { return func(cmd); } } /// <summary> /// <para/>Prepares SqlCommand and pass it to a Func-parameter. /// <para/>Parameter "func" is the code where SqlCommand has to be configured with parameters, execute reader and return result. /// </summary> public async Task<T> GetByCommandAsync<T>(Func<SqlCommand, Task<T>> funcAsync ) { using (var cmd = CreateCommand()) { return await funcAsync(cmd).ConfigureAwait(false); } } private static int ExecuteCommand(SqlCommand cmd) { var returnValueParam = cmd.GetReturnValueParam(); var isConnectionClosed = true; try { isConnectionClosed = cmd.Connection.State == ConnectionState.Closed; if (isConnectionClosed) cmd.Connection.Open(); cmd.ExecuteNonQuery(); } finally { if (isConnectionClosed) cmd.Connection.Close(); } return (int) returnValueParam.Value; } /// <summary> /// <para/>Executes SqlCommand which returns nothing but ReturnValue. /// <para/>Calls ExecuteNonQueryAsync inside. /// <para/>Parameter "action" is the code where SqlCommand has to be configured with parameters. /// <para/>Returns ReturnValue - the value from TSQL "RETURN [Value]" statement. If there is no RETURN in TSQL then returns 0. /// </summary> public Int32 ExecuteCommand (Action<SqlCommand> action) { using (var cmd = CreateCommand()) { cmd.AddReturnValueParam(); action(cmd); return ExecuteCommand(cmd); } } public Int32 Execute (string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) { cmd.AddReturnValueParam(); return ExecuteCommand(cmd); } } public Int32 Execute (string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) { cmd.AddReturnValueParam(); return ExecuteCommand(cmd); } } private static async Task<Int32> ExecuteCommandAsync (SqlCommand cmd) { var returnValueParam = cmd.GetReturnValueParam(); var isConnectionClosed = true; try { isConnectionClosed = cmd.Connection.State == ConnectionState.Closed; if (isConnectionClosed) cmd.Connection.Open(); await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); } finally { if (isConnectionClosed) cmd.Connection.Close(); } return (int) returnValueParam.Value; } /// <summary> /// <para/>Executes SqlCommand which returns nothing but ReturnValue. /// <para/>Calls ExecuteNonQueryAsync inside. /// <para/>Parameter "action" is the code where SqlCommand has to be configured with parameters. /// <para/>Returns ReturnValue - the value from TSQL "RETURN [Value]" statement. If there is no RETURN in TSQL then returns 0. /// </summary> public async Task<Int32> ExecuteCommandAsync (Action<SqlCommand> action) { using (var cmd = CreateCommand()) { cmd.AddReturnValueParam(); action(cmd); return await ExecuteCommandAsync(cmd); } } public async Task<Int32> ExecuteAsync (string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) { cmd.AddReturnValueParam(); return await ExecuteCommandAsync(cmd); } } public async Task<Int32> ExecuteAsync (string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) { cmd.AddReturnValueParam(); return await ExecuteCommandAsync(cmd); } } /// <summary> /// <para>Creates SqlCommand, passes it to Action argument as SqlCommand parameter, returns nothing.</para> /// <para>See GitHub Wiki about this method: <a href="https://github.com/lobodava/artisan-orm/wiki/RepositoryBase-methods-for-SqlCommand-initialization#runcommand">https://github.com/lobodava/artisan-orm/wiki/RepositoryBase-methods-for-SqlCommand-initialization#runcommand</a></para> /// </summary> public void RunCommand(Action<SqlCommand> action) { using (var cmd = CreateCommand()) action(cmd); } public async Task RunCommandAsync(Action<SqlCommand> action) { await Task.Run(() => { using (var cmd = CreateCommand()) action(cmd); } ).ConfigureAwait(false); } #region [ ReadTo, ReadAs ] public T ReadTo<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadTo<T>(); } public T ReadTo<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return cmd.ReadTo<T>(); } public async Task<T> ReadToAsync<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return await cmd.ReadToAsync<T>(); } public async Task<T> ReadToAsync<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return await cmd.ReadToAsync<T>(); } public T ReadAs<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadAs<T>(); } public T ReadAs<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return cmd.ReadAs<T>(); } public async Task<T> ReadAsAsync<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return await cmd.ReadAsAsync<T>(); } public async Task<T> ReadAsAsync<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return await cmd.ReadAsAsync<T>(); } #endregion #region [ ReadToList, ReadAsList ] public IList<T> ReadToList<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadToList<T>(); } public IList<T> ReadToList<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return cmd.ReadToList<T>(); } public async Task<IList<T>> ReadToListAsync<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return await cmd.ReadToListAsync<T>(); } public async Task<IList<T>> ReadToListAsync<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return await cmd.ReadToListAsync<T>(); } public IList<T> ReadAsList<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadAsList<T>(); } public IList<T> ReadAsList<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return cmd.ReadAsList<T>(); } public async Task<IList<T>> ReadAsListAsync<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return await cmd.ReadAsListAsync<T>(); } public async Task<IList<T>> ReadAsListAsync<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return await cmd.ReadAsListAsync<T>(); } #endregion #region [ ReadToObjectRow, ReadAsObjectRow ] public ObjectRow ReadToObjectRow<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadToObjectRow<T>(); } public ObjectRow ReadToObjectRow<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return cmd.ReadToObjectRow<T>(); } public async Task<ObjectRow> ReadToObjectRowAsync<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return await cmd.ReadToObjectRowAsync<T>(); } public async Task<ObjectRow> ReadToObjectRowAsync<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return await cmd.ReadToObjectRowAsync<T>(); } public ObjectRow ReadAsObjectRow(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadAsObjectRow(); } public ObjectRow ReadAsObjectRow(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return cmd.ReadAsObjectRow(); } public async Task<ObjectRow> ReadAsObjectRowAsync(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return await cmd.ReadAsObjectRowAsync(); } public async Task<ObjectRow> ReadAsObjectRowAsync(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return await cmd.ReadAsObjectRowAsync(); } #endregion #region [ ReadToObjectRows, ReadAsObjectRows ] public ObjectRows ReadToObjectRows<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadToObjectRows<T>(); } public ObjectRows ReadToObjectRows<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return cmd.ReadToObjectRows<T>(); } public async Task<ObjectRows> ReadToObjectRowsAsync<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return await cmd.ReadToObjectRowsAsync<T>(); } public async Task<ObjectRows> ReadToObjectRowsAsync<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return await cmd.ReadToObjectRowsAsync<T>(); } public ObjectRows ReadAsObjectRows(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadAsObjectRows(); } public ObjectRows ReadAsObjectRows(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return cmd.ReadAsObjectRows(); } public async Task<ObjectRows> ReadAsObjectRowsAsync(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return await cmd.ReadAsObjectRowsAsync(); } public async Task<ObjectRows> ReadAsObjectRowsAsync(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return await cmd.ReadAsObjectRowsAsync(); } #endregion #region [ ReadToDictionary ] public IDictionary<TKey, TValue> ReadToDictionary<TKey, TValue>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadToDictionary<TKey, TValue>(); } public IDictionary<TKey, TValue> ReadToDictionary<TKey, TValue>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return cmd.ReadToDictionary<TKey, TValue>(); } public IDictionary<TKey, TValue> ReadAsDictionary<TKey, TValue>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadAsDictionary<TKey, TValue>(); } public IDictionary<TKey, TValue> ReadAsDictionary<TKey, TValue>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return cmd.ReadAsDictionary<TKey, TValue>(); } public async Task<IDictionary<TKey, TValue>> ReadToDictionaryAsync<TKey, TValue>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return await cmd.ReadToDictionaryAsync<TKey, TValue>(); } public async Task<IDictionary<TKey, TValue>> ReadToDictionaryAsync<TKey, TValue>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return await cmd.ReadToDictionaryAsync<TKey, TValue>(); } public async Task<IDictionary<TKey, TValue>> ReadAsDictionaryAsync<TKey, TValue>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return await cmd.ReadAsDictionaryAsync<TKey, TValue>(); } public async Task<IDictionary<TKey, TValue>> ReadAsDictionaryAsync<TKey, TValue>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return await cmd.ReadAsDictionaryAsync<TKey, TValue>(); } #endregion #region [ ReadToEnumerable, ReadAsEnumerable ] public IEnumerable<T> ReadToEnumerable<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadToEnumerable<T>(); } public IEnumerable<T> ReadToEnumerable<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return cmd.ReadToEnumerable<T>(); } public IEnumerable<T> ReadAsEnumerable<T>(string sql, params SqlParameter[] sqlParameters) { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadAsEnumerable<T>(); } public IEnumerable<T> ReadAsEnumerable<T>(string sql, Action<SqlCommand> action) { using (var cmd = CreateCommand(sql, action)) return cmd.ReadAsEnumerable<T>(); } #endregion #region [ ReadToTree, ReadToTreeList ] public T ReadToTree<T>(string sql, bool hierarchicallySorted = false, params SqlParameter[] sqlParameters) where T: class, INode<T> { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadToTree<T>(hierarchicallySorted); } public T ReadToTree<T>(string sql, Action<SqlCommand> action, bool hierarchicallySorted = false) where T: class, INode<T> { using (var cmd = CreateCommand(sql, action)) return cmd.ReadToTree<T>(hierarchicallySorted); } public IList<T> ReadToTreeList<T>(string sql, bool hierarchicallySorted = false, params SqlParameter[] sqlParameters) where T: class, INode<T> { using (var cmd = CreateCommand(sql, sqlParameters)) return cmd.ReadToTreeList<T>(hierarchicallySorted); } public IList<T> ReadToTreeList<T>(string sql, Action<SqlCommand> action, bool hierarchicallySorted = false) where T: class, INode<T> { using (var cmd = CreateCommand(sql, action)) return cmd.ReadToTreeList<T>(hierarchicallySorted); } #endregion public void AddParams(SqlCommand cmd, dynamic parameters) { var dict = new Dictionary<string, object>(); foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(parameters)) { object obj = descriptor.GetValue(parameters); dict.Add(descriptor.Name, obj); } cmd.AddParams(dict); } public static void CheckForDataReplyException(SqlDataReader dr) { var statusCode = dr.ReadTo<string>(getNextResult: false); var dataReplyStatus = DataReply.ParseStatus(statusCode); if (dataReplyStatus != null ) { if (dr.NextResult()) throw new DataReplyException(dataReplyStatus.Value, dr.ReadToArray<DataReplyMessage>()); throw new DataReplyException(dataReplyStatus.Value); } dr.NextResult(); } public void Dispose() { Transaction?.Dispose(); Connection?.Dispose(); } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.IO; using SquabPie.Mono.Cecil.Metadata; using RVA = System.UInt32; namespace SquabPie.Mono.Cecil.PE { sealed class ImageReader : BinaryStreamReader { readonly Image image; DataDirectory cli; DataDirectory metadata; public ImageReader (Stream stream) : base (stream) { image = new Image (); image.FileName = stream.GetFullyQualifiedName (); } void MoveTo (DataDirectory directory) { BaseStream.Position = image.ResolveVirtualAddress (directory.VirtualAddress); } void MoveTo (uint position) { BaseStream.Position = position; } void ReadImage () { if (BaseStream.Length < 128) throw new BadImageFormatException (); // - DOSHeader // PE 2 // Start 58 // Lfanew 4 // End 64 if (ReadUInt16 () != 0x5a4d) throw new BadImageFormatException (); Advance (58); MoveTo (ReadUInt32 ()); if (ReadUInt32 () != 0x00004550) throw new BadImageFormatException (); // - PEFileHeader // Machine 2 image.Architecture = ReadArchitecture (); // NumberOfSections 2 ushort sections = ReadUInt16 (); // TimeDateStamp 4 // PointerToSymbolTable 4 // NumberOfSymbols 4 // OptionalHeaderSize 2 Advance (14); // Characteristics 2 ushort characteristics = ReadUInt16 (); ushort subsystem, dll_characteristics; ReadOptionalHeaders (out subsystem, out dll_characteristics); ReadSections (sections); ReadCLIHeader (); ReadMetadata (); image.Kind = GetModuleKind (characteristics, subsystem); image.Characteristics = (ModuleCharacteristics) dll_characteristics; } TargetArchitecture ReadArchitecture () { var machine = ReadUInt16 (); switch (machine) { case 0x014c: return TargetArchitecture.I386; case 0x8664: return TargetArchitecture.AMD64; case 0x0200: return TargetArchitecture.IA64; case 0x01c4: return TargetArchitecture.ARMv7; } throw new NotSupportedException (); } static ModuleKind GetModuleKind (ushort characteristics, ushort subsystem) { if ((characteristics & 0x2000) != 0) // ImageCharacteristics.Dll return ModuleKind.Dll; if (subsystem == 0x2 || subsystem == 0x9) // SubSystem.WindowsGui || SubSystem.WindowsCeGui return ModuleKind.Windows; return ModuleKind.Console; } void ReadOptionalHeaders (out ushort subsystem, out ushort dll_characteristics) { // - PEOptionalHeader // - StandardFieldsHeader // Magic 2 bool pe64 = ReadUInt16 () == 0x20b; // pe32 || pe64 // LMajor 1 // LMinor 1 // CodeSize 4 // InitializedDataSize 4 // UninitializedDataSize4 // EntryPointRVA 4 // BaseOfCode 4 // BaseOfData 4 || 0 // - NTSpecificFieldsHeader // ImageBase 4 || 8 // SectionAlignment 4 // FileAlignement 4 // OSMajor 2 // OSMinor 2 // UserMajor 2 // UserMinor 2 // SubSysMajor 2 // SubSysMinor 2 // Reserved 4 // ImageSize 4 // HeaderSize 4 // FileChecksum 4 Advance (66); // SubSystem 2 subsystem = ReadUInt16 (); // DLLFlags 2 dll_characteristics = ReadUInt16 (); // StackReserveSize 4 || 8 // StackCommitSize 4 || 8 // HeapReserveSize 4 || 8 // HeapCommitSize 4 || 8 // LoaderFlags 4 // NumberOfDataDir 4 // - DataDirectoriesHeader // ExportTable 8 // ImportTable 8 // ResourceTable 8 // ExceptionTable 8 // CertificateTable 8 // BaseRelocationTable 8 Advance (pe64 ? 88 : 72); // Debug 8 image.Debug = ReadDataDirectory (); // Copyright 8 // GlobalPtr 8 // TLSTable 8 // LoadConfigTable 8 // BoundImport 8 // IAT 8 // DelayImportDescriptor8 Advance (56); // CLIHeader 8 cli = ReadDataDirectory (); if (cli.IsZero) throw new BadImageFormatException (); // Reserved 8 Advance (8); } string ReadAlignedString (int length) { int read = 0; var buffer = new char [length]; while (read < length) { var current = ReadByte (); if (current == 0) break; buffer [read++] = (char) current; } Advance (-1 + ((read + 4) & ~3) - read); return new string (buffer, 0, read); } string ReadZeroTerminatedString (int length) { int read = 0; var buffer = new char [length]; var bytes = ReadBytes (length); while (read < length) { var current = bytes [read]; if (current == 0) break; buffer [read++] = (char) current; } return new string (buffer, 0, read); } void ReadSections (ushort count) { var sections = new Section [count]; for (int i = 0; i < count; i++) { var section = new Section (); // Name section.Name = ReadZeroTerminatedString (8); // VirtualSize 4 Advance (4); // VirtualAddress 4 section.VirtualAddress = ReadUInt32 (); // SizeOfRawData 4 section.SizeOfRawData = ReadUInt32 (); // PointerToRawData 4 section.PointerToRawData = ReadUInt32 (); // PointerToRelocations 4 // PointerToLineNumbers 4 // NumberOfRelocations 2 // NumberOfLineNumbers 2 // Characteristics 4 Advance (16); sections [i] = section; ReadSectionData (section); } image.Sections = sections; } void ReadSectionData (Section section) { var position = BaseStream.Position; MoveTo (section.PointerToRawData); var length = (int) section.SizeOfRawData; var data = new byte [length]; int offset = 0, read; while ((read = Read (data, offset, length - offset)) > 0) offset += read; section.Data = data; BaseStream.Position = position; } void ReadCLIHeader () { MoveTo (cli); // - CLIHeader // Cb 4 // MajorRuntimeVersion 2 // MinorRuntimeVersion 2 Advance (8); // Metadata 8 metadata = ReadDataDirectory (); // Flags 4 image.Attributes = (ModuleAttributes) ReadUInt32 (); // EntryPointToken 4 image.EntryPointToken = ReadUInt32 (); // Resources 8 image.Resources = ReadDataDirectory (); // StrongNameSignature 8 image.StrongName = ReadDataDirectory (); // CodeManagerTable 8 // VTableFixups 8 // ExportAddressTableJumps 8 // ManagedNativeHeader 8 } void ReadMetadata () { MoveTo (metadata); if (ReadUInt32 () != 0x424a5342) throw new BadImageFormatException (); // MajorVersion 2 // MinorVersion 2 // Reserved 4 Advance (8); image.RuntimeVersion = ReadZeroTerminatedString (ReadInt32 ()); // Flags 2 Advance (2); var streams = ReadUInt16 (); var section = image.GetSectionAtVirtualAddress (metadata.VirtualAddress); if (section == null) throw new BadImageFormatException (); image.MetadataSection = section; for (int i = 0; i < streams; i++) ReadMetadataStream (section); if (image.TableHeap != null) ReadTableHeap (); } void ReadMetadataStream (Section section) { // Offset 4 uint start = metadata.VirtualAddress - section.VirtualAddress + ReadUInt32 (); // relative to the section start // Size 4 uint size = ReadUInt32 (); var name = ReadAlignedString (16); switch (name) { case "#~": case "#-": image.TableHeap = new TableHeap (section, start, size); break; case "#Strings": image.StringHeap = new StringHeap (section, start, size); break; case "#Blob": image.BlobHeap = new BlobHeap (section, start, size); break; case "#GUID": image.GuidHeap = new GuidHeap (section, start, size); break; case "#US": image.UserStringHeap = new UserStringHeap (section, start, size); break; } } void ReadTableHeap () { var heap = image.TableHeap; uint start = heap.Section.PointerToRawData; MoveTo (heap.Offset + start); // Reserved 4 // MajorVersion 1 // MinorVersion 1 Advance (6); // HeapSizes 1 var sizes = ReadByte (); // Reserved2 1 Advance (1); // Valid 8 heap.Valid = ReadInt64 (); // Sorted 8 heap.Sorted = ReadInt64 (); for (int i = 0; i < TableHeap.TableCount; i++) { if (!heap.HasTable ((Table) i)) continue; heap.Tables [i].Length = ReadUInt32 (); } SetIndexSize (image.StringHeap, sizes, 0x1); SetIndexSize (image.GuidHeap, sizes, 0x2); SetIndexSize (image.BlobHeap, sizes, 0x4); ComputeTableInformations (); } static void SetIndexSize (Heap heap, uint sizes, byte flag) { if (heap == null) return; heap.IndexSize = (sizes & flag) > 0 ? 4 : 2; } int GetTableIndexSize (Table table) { return image.GetTableIndexSize (table); } int GetCodedIndexSize (CodedIndex index) { return image.GetCodedIndexSize (index); } void ComputeTableInformations () { uint offset = (uint) BaseStream.Position - image.MetadataSection.PointerToRawData; // header int stridx_size = image.StringHeap.IndexSize; int blobidx_size = image.BlobHeap != null ? image.BlobHeap.IndexSize : 2; var heap = image.TableHeap; var tables = heap.Tables; for (int i = 0; i < TableHeap.TableCount; i++) { var table = (Table) i; if (!heap.HasTable (table)) continue; int size; switch (table) { case Table.Module: size = 2 // Generation + stridx_size // Name + (image.GuidHeap.IndexSize * 3); // Mvid, EncId, EncBaseId break; case Table.TypeRef: size = GetCodedIndexSize (CodedIndex.ResolutionScope) // ResolutionScope + (stridx_size * 2); // Name, Namespace break; case Table.TypeDef: size = 4 // Flags + (stridx_size * 2) // Name, Namespace + GetCodedIndexSize (CodedIndex.TypeDefOrRef) // BaseType + GetTableIndexSize (Table.Field) // FieldList + GetTableIndexSize (Table.Method); // MethodList break; case Table.FieldPtr: size = GetTableIndexSize (Table.Field); // Field break; case Table.Field: size = 2 // Flags + stridx_size // Name + blobidx_size; // Signature break; case Table.MethodPtr: size = GetTableIndexSize (Table.Method); // Method break; case Table.Method: size = 8 // Rva 4, ImplFlags 2, Flags 2 + stridx_size // Name + blobidx_size // Signature + GetTableIndexSize (Table.Param); // ParamList break; case Table.ParamPtr: size = GetTableIndexSize (Table.Param); // Param break; case Table.Param: size = 4 // Flags 2, Sequence 2 + stridx_size; // Name break; case Table.InterfaceImpl: size = GetTableIndexSize (Table.TypeDef) // Class + GetCodedIndexSize (CodedIndex.TypeDefOrRef); // Interface break; case Table.MemberRef: size = GetCodedIndexSize (CodedIndex.MemberRefParent) // Class + stridx_size // Name + blobidx_size; // Signature break; case Table.Constant: size = 2 // Type + GetCodedIndexSize (CodedIndex.HasConstant) // Parent + blobidx_size; // Value break; case Table.CustomAttribute: size = GetCodedIndexSize (CodedIndex.HasCustomAttribute) // Parent + GetCodedIndexSize (CodedIndex.CustomAttributeType) // Type + blobidx_size; // Value break; case Table.FieldMarshal: size = GetCodedIndexSize (CodedIndex.HasFieldMarshal) // Parent + blobidx_size; // NativeType break; case Table.DeclSecurity: size = 2 // Action + GetCodedIndexSize (CodedIndex.HasDeclSecurity) // Parent + blobidx_size; // PermissionSet break; case Table.ClassLayout: size = 6 // PackingSize 2, ClassSize 4 + GetTableIndexSize (Table.TypeDef); // Parent break; case Table.FieldLayout: size = 4 // Offset + GetTableIndexSize (Table.Field); // Field break; case Table.StandAloneSig: size = blobidx_size; // Signature break; case Table.EventMap: size = GetTableIndexSize (Table.TypeDef) // Parent + GetTableIndexSize (Table.Event); // EventList break; case Table.EventPtr: size = GetTableIndexSize (Table.Event); // Event break; case Table.Event: size = 2 // Flags + stridx_size // Name + GetCodedIndexSize (CodedIndex.TypeDefOrRef); // EventType break; case Table.PropertyMap: size = GetTableIndexSize (Table.TypeDef) // Parent + GetTableIndexSize (Table.Property); // PropertyList break; case Table.PropertyPtr: size = GetTableIndexSize (Table.Property); // Property break; case Table.Property: size = 2 // Flags + stridx_size // Name + blobidx_size; // Type break; case Table.MethodSemantics: size = 2 // Semantics + GetTableIndexSize (Table.Method) // Method + GetCodedIndexSize (CodedIndex.HasSemantics); // Association break; case Table.MethodImpl: size = GetTableIndexSize (Table.TypeDef) // Class + GetCodedIndexSize (CodedIndex.MethodDefOrRef) // MethodBody + GetCodedIndexSize (CodedIndex.MethodDefOrRef); // MethodDeclaration break; case Table.ModuleRef: size = stridx_size; // Name break; case Table.TypeSpec: size = blobidx_size; // Signature break; case Table.ImplMap: size = 2 // MappingFlags + GetCodedIndexSize (CodedIndex.MemberForwarded) // MemberForwarded + stridx_size // ImportName + GetTableIndexSize (Table.ModuleRef); // ImportScope break; case Table.FieldRVA: size = 4 // RVA + GetTableIndexSize (Table.Field); // Field break; case Table.EncLog: size = 8; break; case Table.EncMap: size = 4; break; case Table.Assembly: size = 16 // HashAlgId 4, Version 4 * 2, Flags 4 + blobidx_size // PublicKey + (stridx_size * 2); // Name, Culture break; case Table.AssemblyProcessor: size = 4; // Processor break; case Table.AssemblyOS: size = 12; // Platform 4, Version 2 * 4 break; case Table.AssemblyRef: size = 12 // Version 2 * 4 + Flags 4 + (blobidx_size * 2) // PublicKeyOrToken, HashValue + (stridx_size * 2); // Name, Culture break; case Table.AssemblyRefProcessor: size = 4 // Processor + GetTableIndexSize (Table.AssemblyRef); // AssemblyRef break; case Table.AssemblyRefOS: size = 12 // Platform 4, Version 2 * 4 + GetTableIndexSize (Table.AssemblyRef); // AssemblyRef break; case Table.File: size = 4 // Flags + stridx_size // Name + blobidx_size; // HashValue break; case Table.ExportedType: size = 8 // Flags 4, TypeDefId 4 + (stridx_size * 2) // Name, Namespace + GetCodedIndexSize (CodedIndex.Implementation); // Implementation break; case Table.ManifestResource: size = 8 // Offset, Flags + stridx_size // Name + GetCodedIndexSize (CodedIndex.Implementation); // Implementation break; case Table.NestedClass: size = GetTableIndexSize (Table.TypeDef) // NestedClass + GetTableIndexSize (Table.TypeDef); // EnclosingClass break; case Table.GenericParam: size = 4 // Number, Flags + GetCodedIndexSize (CodedIndex.TypeOrMethodDef) // Owner + stridx_size; // Name break; case Table.MethodSpec: size = GetCodedIndexSize (CodedIndex.MethodDefOrRef) // Method + blobidx_size; // Instantiation break; case Table.GenericParamConstraint: size = GetTableIndexSize (Table.GenericParam) // Owner + GetCodedIndexSize (CodedIndex.TypeDefOrRef); // Constraint break; default: throw new NotSupportedException (); } tables [i].RowSize = (uint) size; tables [i].Offset = offset; offset += (uint) size * tables [i].Length; } } public static Image ReadImageFrom (Stream stream) { try { var reader = new ImageReader (stream); reader.ReadImage (); return reader.image; } catch (EndOfStreamException e) { throw new BadImageFormatException (stream.GetFullyQualifiedName (), e); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Fryhard.DevConfZA2016.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.DoNotCallOverridableMethodsInConstructorsAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.DoNotCallOverridableMethodsInConstructorsAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.UnitTests { public class DoNotCallOverridableMethodsInConstructorsTests { [Fact] public async Task CA2214VirtualMethodCSharp() { await VerifyCS.VerifyAnalyzerAsync(@" class C { C() { SomeMethod(); } protected virtual void SomeMethod() { } } ", GetCA2214CSharpResultAt(6, 9)); } [Fact] public async Task CA2214VirtualMethodCSharpWithScope() { await VerifyCS.VerifyAnalyzerAsync(@" class C { C() { [|SomeMethod()|]; } protected virtual void SomeMethod() { } } "); } [Fact] public async Task CA2214VirtualMethodBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Class C Public Sub New() SomeMethod() End Sub Overridable Sub SomeMethod() End Sub End Class ", GetCA2214BasicResultAt(4, 9)); } [Fact] public async Task CA2214VirtualMethodBasicwithScope() { await VerifyVB.VerifyAnalyzerAsync(@" Class C Public Sub New() [|SomeMethod()|] End Sub Overridable Sub SomeMethod() End Sub End Class "); } [Fact] public async Task CA2214AbstractMethodCSharp() { await VerifyCS.VerifyAnalyzerAsync(@" abstract class C { C() { SomeMethod(); } protected abstract void SomeMethod(); } ", GetCA2214CSharpResultAt(6, 9)); } [Fact] public async Task CA2214AbstractMethodBasic() { await VerifyVB.VerifyAnalyzerAsync(@" MustInherit Class C Public Sub New() SomeMethod() End Sub MustOverride Sub SomeMethod() End Class ", GetCA2214BasicResultAt(4, 9)); } [Fact] public async Task CA2214MultipleInstancesCSharp() { await VerifyCS.VerifyAnalyzerAsync(@" abstract class C { C() { SomeMethod(); SomeOtherMethod(); } protected abstract void SomeMethod(); protected virtual void SomeOtherMethod() { } } ", GetCA2214CSharpResultAt(6, 9), GetCA2214CSharpResultAt(7, 9)); } [Fact] public async Task CA2214MultipleInstancesBasic() { await VerifyVB.VerifyAnalyzerAsync(@" MustInherit Class C Public Sub New() SomeMethod() SomeOtherMethod() End Sub MustOverride Sub SomeMethod() Overridable Sub SomeOtherMethod() End Sub End Class ", GetCA2214BasicResultAt(4, 9), GetCA2214BasicResultAt(5, 9)); } [Fact] public async Task CA2214NotTopLevelCSharp() { await VerifyCS.VerifyAnalyzerAsync(@" abstract class C { C() { if (true) { SomeMethod(); } if (false) { SomeMethod(); // also check unreachable code } } protected abstract void SomeMethod(); } ", GetCA2214CSharpResultAt(8, 13), GetCA2214CSharpResultAt(13, 13)); } [Fact] public async Task CA2214NotTopLevelBasic() { await VerifyVB.VerifyAnalyzerAsync(@" MustInherit Class C Public Sub New() If True Then SomeMethod() End If If False Then SomeMethod() ' also check unreachable code End If End Sub MustOverride Sub SomeMethod() End Class ", GetCA2214BasicResultAt(5, 13), GetCA2214BasicResultAt(9, 13)); } [Fact] public async Task CA2214NoDiagnosticsOutsideConstructorCSharp() { await VerifyCS.VerifyAnalyzerAsync(@" abstract class C { protected abstract void SomeMethod(); void Method() { SomeMethod(); } } "); } [Fact] public async Task CA2214NoDiagnosticsOutsideConstructorBasic() { await VerifyVB.VerifyAnalyzerAsync(@" MustInherit Class C MustOverride Sub SomeMethod() Sub Method() SomeMethod() End Sub End Class "); } [Fact] public async Task CA2214SpecialInheritanceCSharp_Web() { await new VerifyCS.Test { ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithSystemWeb, TestState = { Sources = { @" abstract class C : System.Web.UI.Control { C() { // no diagnostics because we inherit from System.Web.UI.Control SomeMethod(); OnLoad(null); } protected abstract void SomeMethod(); } abstract class F : System.ComponentModel.Component { F() { // no diagnostics because we inherit from System.ComponentModel.Component SomeMethod(); } protected abstract void SomeMethod(); } " }, } }.RunAsync(); } [Fact] public async Task CA2214SpecialInheritanceCSharp_WinForms() { await new VerifyCS.Test { ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithWinForms, TestState = { Sources = { @" abstract class D : System.Windows.Forms.Control { D() { // no diagnostics because we inherit from System.Windows.Forms.Control SomeMethod(); OnPaint(null); } protected abstract void SomeMethod(); } class ControlBase : System.Windows.Forms.Control { } class E : ControlBase { E() { OnGotFocus(null); // no diagnostics when we're not an immediate descendant of a special class } } abstract class F : System.ComponentModel.Component { F() { // no diagnostics because we inherit from System.ComponentModel.Component SomeMethod(); } protected abstract void SomeMethod(); } " }, } }.RunAsync(); } [Fact] public async Task CA2214SpecialInheritanceBasic_WinForms() { await new VerifyVB.Test { ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithWinForms, TestState = { Sources = { @" MustInherit Class D Inherits System.Windows.Forms.Control Public Sub New() ' no diagnostics because we inherit from System.Windows.Forms.Control SomeMethod() OnPaint(Nothing) End Sub MustOverride Sub SomeMethod() End Class Class ControlBase Inherits System.Windows.Forms.Control End Class Class E Inherits ControlBase Public Sub New() OnGotFocus(Nothing) ' no diagnostics when we're not an immediate descendant of a special class End Sub End Class MustInherit Class F Inherits System.ComponentModel.Component Public Sub New() ' no diagnostics because we inherit from System.ComponentModel.Component SomeMethod() End Sub MustOverride Sub SomeMethod() End Class " }, } }.RunAsync(); } [Fact] public async Task CA2214SpecialInheritanceBasic_Web() { await new VerifyVB.Test { ReferenceAssemblies = AdditionalMetadataReferences.DefaultWithSystemWeb, TestState = { Sources = { @" MustInherit Class C Inherits System.Web.UI.Control Public Sub New() ' no diagnostics because we inherit from System.Web.UI.Control SomeMethod() OnLoad(Nothing) End Sub MustOverride Sub SomeMethod() End Class MustInherit Class F Inherits System.ComponentModel.Component Public Sub New() ' no diagnostics because we inherit from System.ComponentModel.Component SomeMethod() End Sub MustOverride Sub SomeMethod() End Class " }, } }.RunAsync(); } [Fact] public async Task CA2214VirtualOnOtherClassesCSharp() { await VerifyCS.VerifyAnalyzerAsync(@" class D { public virtual void SomeMethod() {} } class C { public C(object obj, D d) { if (obj.Equals(d)) { d.SomeMethod(); } } } "); } [Fact] public async Task CA2214VirtualOnOtherClassesBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Class D Public Overridable Sub SomeMethod() End Sub End Class Class C Public Sub New(obj As Object, d As D) If obj.Equals(d) Then d.SomeMethod() End If End Sub End Class "); } [Fact, WorkItem(1652, "https://github.com/dotnet/roslyn-analyzers/issues/1652")] public async Task CA2214VirtualInvocationsInLambdaCSharp() { await VerifyCS.VerifyAnalyzerAsync(@" using System; internal abstract class A { private readonly Lazy<int> _lazyField; protected A() { _lazyField = new Lazy<int>(() => M()); } protected abstract int M(); } "); } [Fact, WorkItem(1652, "https://github.com/dotnet/roslyn-analyzers/issues/1652")] public async Task CA2214VirtualInvocationsInLambdaBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Friend MustInherit Class A Private ReadOnly _lazyField As Lazy(Of Integer) Protected Sub New() _lazyField = New Lazy(Of Integer)(Function() M()) End Sub Protected MustOverride Function M() As Integer End Class "); } [Fact, WorkItem(4142, "https://github.com/dotnet/roslyn-analyzers/issues/4142")] public async Task CA2214_VirtualInvocationsInLambda() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Threading; using System.Threading.Tasks; public class C { private readonly Lazy<Task> _initialization; protected C() { Task RunInit() => this.InitializeAsync(this.DisposeCts.Token); this._initialization = new Lazy<Task>(() => Task.Run(RunInit, this.DisposeCts.Token), isThreadSafe: true); } protected CancellationTokenSource DisposeCts { get; } = new CancellationTokenSource(); protected Task Initialization => this._initialization.Value; protected virtual async Task InitializeAsync(CancellationToken cancellationToken) { // Content doesn't matter } }"); } private static DiagnosticResult GetCA2214CSharpResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic() .WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs private static DiagnosticResult GetCA2214BasicResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic() .WithLocation(line, column); #pragma warning restore RS0030 // Do not used banned APIs } }
// Copyright (C) 2018 Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using GoogleMobileAds.Api; using GoogleMobileAds.Common; namespace GoogleMobileAds.iOS { public class RewardedAdClient : IRewardedAdClient, IDisposable { private IntPtr rewardedAdPtr; private IntPtr rewardedAdClientPtr; #region rewarded callback types internal delegate void GADURewardedAdDidReceiveAdCallback( IntPtr rewardedAdClient); internal delegate void GADURewardedAdDidFailToReceiveAdWithErrorCallback( IntPtr rewardedAdClient, string error); internal delegate void GADURewardedAdDidFailToShowAdWithErrorCallback( IntPtr rewardedAdClient, string error); internal delegate void GADURewardedAdDidOpenCallback( IntPtr rewardedAdClient); internal delegate void GADURewardedAdDidCloseCallback( IntPtr rewardedAdClient); internal delegate void GADUUserEarnedRewardCallback( IntPtr rewardedAdClient, string rewardType, double rewardAmount); internal delegate void GADURewardedAdPaidEventCallback( IntPtr rewardedAdClient, int precision, long value, string currencyCode); #endregion public event EventHandler<EventArgs> OnAdLoaded; public event EventHandler<AdErrorEventArgs> OnAdFailedToLoad; public event EventHandler<AdErrorEventArgs> OnAdFailedToShow; public event EventHandler<EventArgs> OnAdOpening; public event EventHandler<EventArgs> OnAdStarted; public event EventHandler<EventArgs> OnAdClosed; public event EventHandler<Reward> OnUserEarnedReward; public event EventHandler<AdValueEventArgs> OnPaidEvent; // This property should be used when setting the rewardedAdPtr. private IntPtr RewardedAdPtr { get { return this.rewardedAdPtr; } set { Externs.GADURelease(this.rewardedAdPtr); this.rewardedAdPtr = value; } } #region IGoogleMobileAdsRewardedAdClient implementation // Creates a rewarded ad. public void CreateRewardedAd(string adUnitId) { this.rewardedAdClientPtr = (IntPtr)GCHandle.Alloc(this); this.RewardedAdPtr = Externs.GADUCreateRewardedAd( this.rewardedAdClientPtr, adUnitId); Externs.GADUSetRewardedAdCallbacks( this.RewardedAdPtr, RewardedAdDidReceiveAdCallback, RewardedAdDidFailToReceiveAdWithErrorCallback, RewardedAdDidFailToShowAdWithErrorCallback, RewardedAdDidOpenCallback, RewardedAdDidCloseCallback, RewardedAdUserDidEarnRewardCallback, RewardedAdPaidEventCallback); } // Load an ad. public void LoadAd(AdRequest request) { IntPtr requestPtr = Utils.BuildAdRequest(request); Externs.GADURequestRewardedAd(this.RewardedAdPtr, requestPtr); Externs.GADURelease(requestPtr); } // Show the rewarded ad on the screen. public void Show() { Externs.GADUShowRewardedAd(this.RewardedAdPtr); } // Sets the server side verification options public void SetServerSideVerificationOptions(ServerSideVerificationOptions serverSideVerificationOptions) { IntPtr optionsPtr = Utils.BuildServerSideVerificationOptions(serverSideVerificationOptions); Externs.GADURewardedAdSetServerSideVerificationOptions(this.RewardedAdPtr, optionsPtr); Externs.GADURelease(optionsPtr); } public bool IsLoaded() { return Externs.GADURewardedAdReady(this.RewardedAdPtr); } // Returns the reward item for the loaded rewarded ad. public Reward GetRewardItem() { string type = Externs.GADURewardedAdGetRewardType(this.RewardedAdPtr); double amount = Externs.GADURewardedAdGetRewardAmount(this.RewardedAdPtr);; return new Reward() { Type = type, Amount = amount }; } // Returns the mediation adapter class name. public string MediationAdapterClassName() { return Utils.PtrToString( Externs.GADUMediationAdapterClassNameForRewardedAd(this.RewardedAdPtr)); } // Destroys the rewarded ad. public void DestroyRewardedAd() { this.RewardedAdPtr = IntPtr.Zero; } public void Dispose() { this.DestroyRewardedAd(); ((GCHandle)this.rewardedAdClientPtr).Free(); } ~RewardedAdClient() { this.Dispose(); } #endregion #region Rewarded ad callback methods [MonoPInvokeCallback(typeof(GADURewardedAdDidReceiveAdCallback))] private static void RewardedAdDidReceiveAdCallback(IntPtr rewardedAdClient) { RewardedAdClient client = IntPtrToRewardedAdClient(rewardedAdClient); if (client.OnAdLoaded != null) { client.OnAdLoaded(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADURewardedAdDidFailToReceiveAdWithErrorCallback))] private static void RewardedAdDidFailToReceiveAdWithErrorCallback( IntPtr rewardedAdClient, string error) { RewardedAdClient client = IntPtrToRewardedAdClient(rewardedAdClient); if (client.OnAdFailedToLoad != null) { AdErrorEventArgs args = new AdErrorEventArgs() { Message = error }; client.OnAdFailedToLoad(client, args); } } [MonoPInvokeCallback(typeof(GADURewardedAdDidFailToShowAdWithErrorCallback))] private static void RewardedAdDidFailToShowAdWithErrorCallback( IntPtr rewardedAdClient, string error) { RewardedAdClient client = IntPtrToRewardedAdClient(rewardedAdClient); if (client.OnAdFailedToShow != null) { AdErrorEventArgs args = new AdErrorEventArgs() { Message = error }; client.OnAdFailedToShow(client, args); } } [MonoPInvokeCallback(typeof(GADURewardedAdDidOpenCallback))] private static void RewardedAdDidOpenCallback(IntPtr rewardedAdClient) { RewardedAdClient client = IntPtrToRewardedAdClient(rewardedAdClient); if (client.OnAdOpening != null) { client.OnAdOpening(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADURewardedAdDidCloseCallback))] private static void RewardedAdDidCloseCallback(IntPtr rewardedAdClient) { RewardedAdClient client = IntPtrToRewardedAdClient( rewardedAdClient); if (client.OnAdClosed != null) { client.OnAdClosed(client, EventArgs.Empty); } } [MonoPInvokeCallback(typeof(GADUUserEarnedRewardCallback))] private static void RewardedAdUserDidEarnRewardCallback( IntPtr rewardedAdClient, string rewardType, double rewardAmount) { RewardedAdClient client = IntPtrToRewardedAdClient( rewardedAdClient); if (client.OnUserEarnedReward != null) { Reward args = new Reward() { Type = rewardType, Amount = rewardAmount }; client.OnUserEarnedReward(client, args); } } [MonoPInvokeCallback(typeof(GADURewardedAdPaidEventCallback))] private static void RewardedAdPaidEventCallback( IntPtr rewardedAdClient, int precision, long value, string currencyCode) { RewardedAdClient client = IntPtrToRewardedAdClient(rewardedAdClient); if (client.OnPaidEvent != null) { AdValue adValue = new AdValue() { Precision = (AdValue.PrecisionType)precision, Value = value, CurrencyCode = currencyCode }; AdValueEventArgs args = new AdValueEventArgs() { AdValue = adValue }; client.OnPaidEvent(client, args); } } private static RewardedAdClient IntPtrToRewardedAdClient( IntPtr rewardedAdClient) { GCHandle handle = (GCHandle)rewardedAdClient; return handle.Target as RewardedAdClient; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; using System.Web.Script.Serialization; namespace Pcc { public class PrizmApplicationServices { /// <summary> /// Forwards any given request to PrizmApplicationServices /// </summary> /// <param name="context">The HTTP Context that will be used to access both request and response</param> /// <param name="path">The path that will be used to invoke PrizmApplicationServices</param> public static void ForwardRequest(HttpContext context, string path) { // Create a request with same data in navigator request var request = GetProxyRequest(context, context.Request.HttpMethod, path, context.Request.Url.Query); // Send the request to the remote server and return the response HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { response = (HttpWebResponse)ex.Response; } // Set current response based on the PAS response UpdateContextResponse(context, response); // Close streams response.Close(); context.Response.End(); } /// <summary> /// Creates a new viewing session from a file /// </summary> /// <param name="filePath">The full path of the file that will be uploaded</param> public static string CreateSessionFromFileUpload(string filePath) { var fileInfo = new FileInfo(filePath); var query = new NameValueCollection(); query["fileId"] = fileInfo.Name; query["fileExtension"] = fileInfo.Extension; var emptySessionRequest = GetProxyRequestWithQuery(HttpContext.Current, "GET", "/CreateSession", query); var response = (HttpWebResponse)emptySessionRequest.GetResponse(); var json = new StreamReader(response.GetResponseStream()).ReadToEnd(); var responseData = JsonToDictionary(json); var viewingSessionId = responseData["viewingSessionId"].ToString(); var uploadUrl = PccConfig.WebTierAddress + string.Format("/CreateSession/u{0}", viewingSessionId); using (var client = new WebClient()) { client.UploadFile(uploadUrl, "PUT", filePath); } return viewingSessionId; } /// <summary> /// Creates a new viewing session from an existing document in document storage /// </summary> /// <param name="documentName">The name of the document</param> public static string CreateSessionFromDocument(string documentName) { var query = new NameValueCollection(); query["document"] = documentName; var request = GetProxyRequestWithQuery(HttpContext.Current, "GET", "/CreateSession", query); var response = (HttpWebResponse)request.GetResponse(); var json = new StreamReader(response.GetResponseStream()).ReadToEnd(); var responseData = JsonToDictionary(json); var viewingSessionId = responseData["viewingSessionId"].ToString(); return viewingSessionId; } /// <summary> /// Creates a new viewing session from an existing form /// </summary> /// <param name="formId">The ID of the previously saved form</param> public static string CreateSessionFromForm(string formId) { var query = new NameValueCollection(); query["form"] = formId; var request = GetProxyRequestWithQuery(HttpContext.Current, "GET", "/CreateSession", query); var response = (HttpWebResponse)request.GetResponse(); var json = new StreamReader(response.GetResponseStream()).ReadToEnd(); var responseData = JsonToDictionary(json); var viewingSessionId = responseData["viewingSessionId"].ToString(); return viewingSessionId; } private static HttpWebRequest GetProxyRequest(HttpContext context, string method, string path, string query) { var cookieContainer = new CookieContainer(); // Create a request to the server var request = CreatePasRequest(method, path, query); request.KeepAlive = true; request.CookieContainer = cookieContainer; // Set special headers if (context.Request.AcceptTypes != null && context.Request.AcceptTypes.Any()) { request.Accept = string.Join(",", context.Request.AcceptTypes); } request.ContentType = context.Request.ContentType; request.UserAgent = context.Request.UserAgent; // Copy headers foreach (var headerKey in context.Request.Headers.AllKeys) { if (WebHeaderCollection.IsRestricted(headerKey)) { continue; } request.Headers[headerKey] = context.Request.Headers[headerKey]; } // Send Cookie extracted from the original request for (var i = 0; i < context.Request.Cookies.Count; i++) { var navigatorCookie = context.Request.Cookies[i]; var c = new Cookie(navigatorCookie.Name, navigatorCookie.Value) { Domain = request.RequestUri.Host, Expires = navigatorCookie.Expires, HttpOnly = navigatorCookie.HttpOnly, Path = navigatorCookie.Path, Secure = navigatorCookie.Secure }; cookieContainer.Add(c); } // Write the body extracted from the incoming request if (request.Method != "GET" && request.Method != "HEAD") { context.Request.InputStream.Position = 0; var clientStream = context.Request.InputStream; var clientPostData = new byte[context.Request.InputStream.Length]; clientStream.Read(clientPostData, 0, (int)context.Request.InputStream.Length); request.ContentType = context.Request.ContentType; request.ContentLength = clientPostData.Length; var stream = request.GetRequestStream(); stream.Write(clientPostData, 0, clientPostData.Length); stream.Close(); } return request; } private static HttpWebRequest GetProxyRequestWithQuery(HttpContext context, string method, string path = "", NameValueCollection query = null) { var queryString = ""; if (query != null) { queryString = ToQueryString(query); } return GetProxyRequest(context, method, path, queryString); } private static byte[] GetResponseStreamBytes(WebResponse response) { const int bufferSize = 256; var buffer = new byte[bufferSize]; var memoryStream = new MemoryStream(); var responseStream = response.GetResponseStream(); var remoteResponseCount = responseStream.Read(buffer, 0, bufferSize); while (remoteResponseCount > 0) { memoryStream.Write(buffer, 0, remoteResponseCount); remoteResponseCount = responseStream.Read(buffer, 0, bufferSize); } var responseData = memoryStream.ToArray(); memoryStream.Close(); responseStream.Close(); memoryStream.Dispose(); responseStream.Dispose(); return responseData; } private static void UpdateContextResponse(HttpContext context, HttpWebResponse response) { // Copy headers foreach (var headerKey in response.Headers.AllKeys) { if (WebHeaderCollection.IsRestricted(headerKey)) { continue; } context.Response.AddHeader(headerKey, response.Headers[headerKey]); } context.Response.ContentType = response.ContentType; context.Response.Cookies.Clear(); foreach (Cookie receivedCookie in response.Cookies) { var c = new HttpCookie(receivedCookie.Name, receivedCookie.Value) { Domain = context.Request.Url.Host, Expires = receivedCookie.Expires, HttpOnly = receivedCookie.HttpOnly, Path = receivedCookie.Path, Secure = receivedCookie.Secure }; context.Response.Cookies.Add(c); } var responseData = GetResponseStreamBytes(response); // Send the response to client context.Response.ContentEncoding = Encoding.UTF8; context.Response.ContentType = response.ContentType; context.Response.OutputStream.Write(responseData, 0, responseData.Length); context.Response.StatusCode = (int)response.StatusCode; } private static HttpWebRequest CreatePasRequest(string method, string path = "", string queryString = "") { queryString = queryString ?? ""; if (queryString.StartsWith("?")) { queryString = queryString.Remove(0, 1); } var uriBuilder = new UriBuilder(PccConfig.PrizmApplicationServicesScheme, PccConfig.PrizmApplicationServicesHost, PccConfig.PrizmApplicationServicesPort, path) { Query = queryString }; var url = uriBuilder.ToString(); var request = (HttpWebRequest)WebRequest.Create(url); request.Method = method.ToUpper().Trim(); return request; } private static string ToQueryString(NameValueCollection nvc) { var list = new List<string>(); foreach (var key in nvc.AllKeys) { foreach (var value in nvc.GetValues(key)) { list.Add(string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value))); } } return string.Join("&", list.ToArray()); } private static Dictionary<string, object> JsonToDictionary(string json) { var serializer = new JavaScriptSerializer(); return serializer.Deserialize<Dictionary<string, object>>(json); } } }
using System.ServiceModel; using System.Xml; using Caliburn.Micro; using csShared; using csShared.Geo; using csShared.Utils; using ESRI.ArcGIS.Client; using ESRI.ArcGIS.Client.Geometry; using ESRI.ArcGIS.Client.Projection; using ESRI.ArcGIS.Client.Symbols; using IMB3; using System; using System.Collections.ObjectModel; using System.IO; using System.Timers; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Threading; using TestFoV.FieldOfViewService; using Brushes = System.Windows.Media.Brushes; using Color = System.Drawing.Color; using Point = System.Windows.Point; using PointCollection = ESRI.ArcGIS.Client.Geometry.PointCollection; namespace csGeoLayers.MapTools.FieldOfViewTool { public class FieldOfView : PropertyChangedBase { private readonly Timer updateTimer = new Timer(); private readonly WebMercator webMercator = new WebMercator(); public csPoint FinishPoint; public GroupLayer Layer; public Graphic Line; public ElementLayer ImageLayer; public Image Image; public GraphicsLayer MLayer; public csPoint StartPoint; private TEventEntry _3D; private Graphic attachedFinish; private Graphic attachedStart; private double distance; public Graphic Finish; private bool firstMovement = true; private string lastMes; private bool rotating; private string rotatingState; public Graphic Start; /* <binding name ="BasicHttpBinding_IFieldOfViewService" maxBufferPoolSize="67108864" maxBufferSize="67108864" maxReceivedMessageSize="67108864" transferMode="Streamed"> <readerQuotas maxDepth ="32" maxStringContentLength="5242880" maxArrayLength="2147483646" maxBytesPerRead="4096" maxNameTableCharCount="5242880" /> </binding> */ private static readonly BasicHttpBinding DefaultBinding = new BasicHttpBinding { MaxBufferPoolSize = 67108864, MaxBufferSize = 67108864, MaxReceivedMessageSize = 67108864, TransferMode = TransferMode.Streamed, ReaderQuotas = new XmlDictionaryReaderQuotas { MaxDepth = 32, MaxStringContentLength = 5242880, MaxArrayLength = 2147483646, MaxBytesPerRead = 4096, MaxNameTableCharCount = 5242880 } }; //<!--<endpoint address="http://cool3.sensorlab.tno.nl:8035/FieldOfView" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IFieldOfViewService" contract="FieldOfViewService.IFieldOfViewService" name="OnlineFieldOfViewService" /> //<endpoint address="http://localhost:8035/FieldOfView" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IFieldOfViewService" contract="FieldOfViewService.IFieldOfViewService" name="LocalFieldOfViewService" />--> private readonly FieldOfViewServiceClient remoteClient = new FieldOfViewServiceClient(DefaultBinding, new EndpointAddress(new Uri(AppState.Config.Get("FieldOfView.OnlineEndPointUrl", "http://cool3.sensorlab.tno.nl:8035/FieldOfView")))); private readonly FieldOfViewServiceClient localClient = new FieldOfViewServiceClient(DefaultBinding, new EndpointAddress(new Uri(AppState.Config.Get("FieldOfView.OfflineEndPointUrl", "http://localhost:8035/FieldOfView")))); private bool autoHeight = true; private DispatcherTimer dtr; private static AppStateSettings AppState { get { return AppStateSettings.Instance; } } public double Distance { get { return distance; } set { distance = value; NotifyOfPropertyChange(() => Distance); } } public bool AutoHeight { get { return autoHeight; } set { autoHeight = value; NotifyOfPropertyChange(() => AutoHeight); } } public double GetDistance() { var p1 = webMercator.ToGeographic(StartPoint.Mp) as MapPoint; var p2 = webMercator.ToGeographic(FinishPoint.Mp) as MapPoint; if (p1 == null || p2 == null) return 0; var pLon1 = p1.X; var pLat1 = p1.Y; var pLon2 = p2.X; var pLat2 = p2.Y; var dist = CoordinateUtils.Distance(pLat1, pLon1, pLat2, pLon2, 'K'); return dist; //Math.Sqrt((deltaX*deltaX) + (deltaY*deltaY)); } public void Init(GroupLayer gl, MapPoint start, MapPoint finish, ResourceDictionary rd) { remoteClient.ComputeFieldOfViewAsImageCompleted += ClientOnComputeFieldOfViewCompleted; localClient .ComputeFieldOfViewAsImageCompleted += ClientOnComputeFieldOfViewCompleted; StartPoint = new csPoint { Mp = start }; FinishPoint = new csPoint { Mp = finish }; MLayer = new GraphicsLayer { ID = Guid.NewGuid().ToString() }; ImageLayer = new ElementLayer(); Image = new System.Windows.Controls.Image { HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch, Stretch = Stretch.Fill, StretchDirection = StretchDirection.Both }; ElementLayer.SetEnvelope(Image, AppState.ViewDef.MapControl.Extent); ImageLayer.Children.Add(Image); Start = new Graphic(); Finish = new Graphic(); Line = new Graphic(); var ls = new LineSymbol { Color = Brushes.Black, Width = 4 }; Line.Symbol = ls; UpdateLine(); MLayer.Graphics.Add(Line); Start.Geometry = start; Start.Symbol = rd["Start"] as Symbol; Start.Attributes["position"] = start; Start.Attributes["finish"] = Finish; Start.Attributes["start"] = Start; Start.Attributes["line"] = Line; Start.Attributes["state"] = "start"; Start.Attributes["measure"] = this; Start.Attributes["menuenabled"] = true; MLayer.Graphics.Add(Start); Finish.Geometry = finish; Finish.Attributes["position"] = finish; Finish.Symbol = rd["Finish"] as Symbol; Finish.Attributes["finish"] = Finish; Finish.Attributes["start"] = Start; Finish.Attributes["line"] = Line; Finish.Attributes["measure"] = this; Finish.Attributes["state"] = "finish"; Finish.Attributes["menuenabled"] = true; MLayer.Graphics.Add(Finish); Layer.ChildLayers.Add(ImageLayer); Layer.ChildLayers.Add(MLayer); MLayer.Initialize(); AppStateSettings.Instance.ViewDef.MapManipulationDelta += ViewDef_MapManipulationDelta; if (AppState.Imb != null && AppState.Imb.Imb != null) { _3D = AppState.Imb.Imb.Publish(AppState.Imb.Imb.ClientHandle + ".3d"); //AppState.Imb.Imb.Publish(_channel); } updateTimer.Interval = 50; updateTimer.Elapsed += UpdateTimerElapsed; updateTimer.Start(); } private void ClientOnComputeFieldOfViewCompleted(object sender, ComputeFieldOfViewAsImageCompletedEventArgs e) { if (e.Error != null) { Logger.Log("Field of View", "Error showing field of view result", e.Error.Message, Logger.Level.Error, true); return; } var result = e.Result; if (result == null || result.ByteBuffer == null) return; var image = ConvertToBitmapImage(result); Execute.OnUIThread(() => { Image.Source = image; }); var env = webMercator.FromGeographic(new Envelope(e.Result.BoundingBox.MinimumLongitude, e.Result.BoundingBox.MinimumLatitude, e.Result.BoundingBox.MaximumLongitude, e.Result.BoundingBox.MaximumLatitude)) as Envelope; ElementLayer.SetEnvelope(Image, env); } private static BitmapImage ConvertToBitmapImage(FieldOfViewAsImageResponse result) { var bitmapImage = new BitmapImage(); using (var mem = new MemoryStream(result.ByteBuffer)) { mem.Position = 0; bitmapImage.BeginInit(); bitmapImage.CreateOptions = BitmapCreateOptions.PreservePixelFormat; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.UriSource = null; bitmapImage.StreamSource = mem; bitmapImage.EndInit(); } bitmapImage.Freeze(); return bitmapImage; } //private static Image ByteArrayToImage(byte[] byteArrayIn) //{ // using (var ms = new MemoryStream(byteArrayIn)) // { // return System.Drawing.Image.FromStream(ms); // } //} private void UpdateTimerElapsed(object sender, ElapsedEventArgs e) { if (AppState.Imb != null && AppState.Imb.IsConnected) { if (!string.IsNullOrEmpty(lastMes)) _3D.SignalString(lastMes); } lastMes = ""; } private void ViewDef_MapManipulationDelta(object sender, EventArgs e) { UpdateLine(); } public void RemoveImage() { Image.Source = null; } public void Calculate() { if (StartPoint == null || StartPoint .Mp == null) return; if (FinishPoint == null || FinishPoint.Mp == null) return; var d = GetDistance() * 1000; var mp = webMercator.ToGeographic(StartPoint.Mp) as MapPoint; if (mp == null) return; var request2 = new FieldOfViewAsImageRequest { CameraLocation = new Location { Longitude = mp.X, Latitude = mp.Y, Altitude = 2 }, MinVisualRange = 0, MaxVisualRange = d, DesiredFieldOfView = d, Orientation = 0, ViewAngle = 360, Mode = ModeOfOperation.NormalRadar, Mask = Masks.None, Color = Color.FromArgb(128, Color.Blue) }; if (AppState.IsOnline) remoteClient.ComputeFieldOfViewAsImageAsync(request2); else localClient.ComputeFieldOfViewAsImageAsync(request2); } private void UpdateLine() { var pl = new Polyline { Paths = new ObservableCollection<PointCollection>() }; var pc = new PointCollection { StartPoint.Mp, FinishPoint.Mp }; pl.Paths.Add(pc); Line.Geometry = pl; } internal void Remove() { RemoveImage(); Layer.ChildLayers.Remove(MLayer); Layer.ChildLayers.Remove(ImageLayer); StopRotation(); } public void Attach(string state, Graphic g) { if (g == null) return; firstMovement = true; firstMoveState = state; switch (state) { case "start": attachedStart = g; UpdatePoint("start", attachedStart.Geometry as MapPoint); g.PropertyChanged += (e, s) => { if (s.PropertyName == "Geometry" && attachedStart != null) { UpdatePoint("start", attachedStart.Geometry as MapPoint); } }; break; case "finish": attachedFinish = g; UpdatePoint("finish", attachedFinish.Geometry as MapPoint); g.PropertyChanged += (e, s) => { if (s.PropertyName == "Geometry" && attachedFinish != null) { UpdatePoint("finish", attachedFinish.Geometry as MapPoint); } }; break; } } private string firstMoveState; private double rotateFixAngle; public bool RotateFix { get; set; } public void FixRotation(string state) { var sp = webMercator.ToGeographic(StartPoint.Mp) as MapPoint; var fp = webMercator.ToGeographic(FinishPoint.Mp) as MapPoint; if (fp == null || sp == null) return; RotateFix = true; var c1 = AppStateSettings.Instance.ViewDef.MapPoint(new KmlPoint(sp.X, sp.Y)); var c2 = AppStateSettings.Instance.ViewDef.MapPoint(new KmlPoint(fp.X, fp.Y)); var angle = 360 - Angle(c1.X, c1.Y, c2.X, c2.Y); rotateFixAngle = angle % 360; switch (state) { case "start": var o = Convert.ToDouble(attachedStart.Attributes.ContainsKey("Orientation")); attachedStart.AttributeValueChanged += (e, s) => { if (!attachedStart.Attributes.ContainsKey("Orientation")) return; var no = Convert.ToDouble(attachedStart.Attributes["Orientation"]); var na = (no - o) + rotateFixAngle; var d1 = Math.Abs(FinishPoint.Mp.X - StartPoint.Mp.X); d1 = d1*d1; var d2 = Math.Abs(FinishPoint.Mp.Y - StartPoint.Mp.Y); d2 = d2*d2; var d = Math.Sqrt(d1 + d2); FinishPoint.Mp.Y = StartPoint.Mp.Y + (int) Math.Round(d*Math.Cos((na/180)*Math.PI)); FinishPoint.Mp.X = StartPoint.Mp.X + (int) Math.Round(d*Math.Sin((na/180)*Math.PI)); Console.WriteLine(d); }; break; } } internal void UpdatePoint(string state, MapPoint geometry) { if (firstMovement) { if (string.IsNullOrEmpty(firstMoveState)) { firstMoveState = state; } else if (firstMoveState != state) { firstMovement = false; } else { firstMoveState = state; } } switch (state) { case "start": if (StartPoint == null || Start == null) break; if (firstMovement) { FinishPoint.Mp.X += geometry.X - StartPoint.Mp.X; FinishPoint.Mp.Y += geometry.Y - StartPoint.Mp.Y; } StartPoint.Mp = geometry; Start.Geometry = geometry; break; case "finish": if (FinishPoint == null || Finish == null) break; if (firstMovement) { StartPoint.Mp.X += geometry.X - FinishPoint.Mp.X; StartPoint.Mp.Y += geometry.Y - FinishPoint.Mp.Y; } //_firstMovement = false; FinishPoint.Mp = geometry; Finish.Geometry = geometry; break; } UpdateLine(); Distance = GetDistance(); } private static double Angle(double px1, double py1, double px2, double py2) { // Negate X and Y values var pxRes = px2 - px1; var pyRes = py2 - py1; double angle; // Calculate the angle if (pxRes == 0.0) { if (pxRes == 0.0) angle = 0.0; else if (pyRes > 0.0) angle = Math.PI / 2.0; else angle = Math.PI * 3.0 / 2.0; } else if (pyRes == 0.0) { angle = pxRes > 0.0 ? 0.0 : Math.PI; } else { if (pxRes < 0.0) angle = Math.Atan(pyRes / pxRes) + Math.PI; else if (pyRes < 0.0) angle = Math.Atan(pyRes / pxRes) + (2 * Math.PI); else angle = Math.Atan(pyRes / pxRes); } // Convert to degrees angle = angle * 180 / Math.PI; return angle; } private void dtr_Tick(object sender, EventArgs e) { if (rotating) { firstMovement = false; switch (rotatingState) { case "start": var angles = Angle(StartPoint.Mp.X, StartPoint.Mp.Y, FinishPoint.Mp.X, FinishPoint.Mp.Y); var deltaXs = StartPoint.Mp.X - FinishPoint.Mp.X; var deltaYs = StartPoint.Mp.Y - FinishPoint.Mp.Y; var distances = Math.Sqrt((deltaXs * deltaXs) + (deltaYs * deltaYs)); angles += 1; angles = ((angles - 180) / 360) * 2 * Math.PI; var ys = (int)Math.Round(FinishPoint.Mp.Y + distances * Math.Sin(angles)); ; var xs = (int)Math.Round(FinishPoint.Mp.X + distances * Math.Cos(angles)); UpdatePoint("start", new MapPoint(xs, ys)); break; case "finish": var angle = Angle(FinishPoint.Mp.X, FinishPoint.Mp.Y, StartPoint.Mp.X, StartPoint.Mp.Y); var deltaX = StartPoint.Mp.X - FinishPoint.Mp.X; var deltaY = StartPoint.Mp.Y - FinishPoint.Mp.Y; var distance = Math.Sqrt((deltaX * deltaX) + (deltaY * deltaY)); angle += 1; angle = ((angle - 180) / 360) * 2 * Math.PI; var y = (int)Math.Round(StartPoint.Mp.Y + distance * Math.Sin(angle)); ; var x = (int)Math.Round(StartPoint.Mp.X + distance * Math.Cos(angle)); UpdatePoint("finish", new MapPoint(x, y)); break; } //MapPoint mp = new MapPoint(this.Position.X + 10, this.Position.Y + 10); //UpdatePoint(_state, mp); } else { dtr.Stop(); } } internal void StopRotation() { rotating = false; } internal void StartRotation(string state) { if (dtr != null && dtr.IsEnabled) dtr.Stop(); rotatingState = state; rotating = true; dtr = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 0, 100) }; dtr.Tick += dtr_Tick; dtr.Start(); } internal void Detach(string _state) { firstMoveState = null; switch (_state) { case "start": attachedStart = null; break; case "finish": attachedFinish = null; break; } } } }
// 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; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; namespace System.Security.Principal { public class IdentityReferenceCollection : ICollection<IdentityReference> { #region Private members // // Container enumerated by this collection // private readonly List<IdentityReference> _Identities; #endregion #region Constructors // // Creates an empty collection of default size // public IdentityReferenceCollection() : this(0) { } // // Creates an empty collection of given initial size // public IdentityReferenceCollection(int capacity) { _Identities = new List<IdentityReference>(capacity); } #endregion #region ICollection<IdentityReference> implementation public void CopyTo(IdentityReference[] array, int offset) { _Identities.CopyTo(0, array, offset, Count); } public int Count { get { return _Identities.Count; } } bool ICollection<IdentityReference>.IsReadOnly { get { return false; } } public void Add(IdentityReference identity) { if (identity == null) { throw new ArgumentNullException("identity"); } Contract.EndContractBlock(); _Identities.Add(identity); } public bool Remove(IdentityReference identity) { if (identity == null) { throw new ArgumentNullException("identity"); } Contract.EndContractBlock(); if (Contains(identity)) { return _Identities.Remove(identity); } return false; } public void Clear() { _Identities.Clear(); } public bool Contains(IdentityReference identity) { if (identity == null) { throw new ArgumentNullException("identity"); } Contract.EndContractBlock(); return _Identities.Contains(identity); } #endregion #region IEnumerable<IdentityReference> implementation IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<IdentityReference> GetEnumerator() { return new IdentityReferenceEnumerator(this); } #endregion #region Public methods public IdentityReference this[int index] { get { return _Identities[index]; } set { if (value == null) { throw new ArgumentNullException("value"); } Contract.EndContractBlock(); _Identities[index] = value; } } internal List<IdentityReference> Identities { get { return _Identities; } } public IdentityReferenceCollection Translate(Type targetType) { return Translate(targetType, false); } public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess) { if (targetType == null) { throw new ArgumentNullException("targetType"); } // // Target type must be a subclass of IdentityReference // if (!targetType.GetTypeInfo().IsSubclassOf(typeof(IdentityReference))) { throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, "targetType"); } Contract.EndContractBlock(); // // if the source collection is empty, just return an empty collection // if (Identities.Count == 0) { return new IdentityReferenceCollection(); } int SourceSidsCount = 0; int SourceNTAccountsCount = 0; // // First, see how many of each of the source types we have. // The cases where source type == target type require no conversion. // for (int i = 0; i < Identities.Count; i++) { Type type = Identities[i].GetType(); if (type == targetType) { continue; } else if (type == typeof(SecurityIdentifier)) { SourceSidsCount += 1; } else if (type == typeof(NTAccount)) { SourceNTAccountsCount += 1; } else { // // Rare case that we have defined a type of identity reference and not included it in the code logic above. // To avoid this we do not allow IdentityReference to be subclassed outside of the BCL. // Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic."); throw new NotSupportedException(); } } bool Homogeneous = false; IdentityReferenceCollection SourceSids = null; IdentityReferenceCollection SourceNTAccounts = null; if (SourceSidsCount == Count) { Homogeneous = true; SourceSids = this; } else if (SourceSidsCount > 0) { SourceSids = new IdentityReferenceCollection(SourceSidsCount); } if (SourceNTAccountsCount == Count) { Homogeneous = true; SourceNTAccounts = this; } else if (SourceNTAccountsCount > 0) { SourceNTAccounts = new IdentityReferenceCollection(SourceNTAccountsCount); } // // Repackage only if the source is not homogeneous (contains different source types) // IdentityReferenceCollection Result = null; if (!Homogeneous) { Result = new IdentityReferenceCollection(Identities.Count); for (int i = 0; i < Identities.Count; i++) { IdentityReference id = this[i]; Type type = id.GetType(); if (type == targetType) { continue; } else if (type == typeof(SecurityIdentifier)) { SourceSids.Add(id); } else if (type == typeof(NTAccount)) { SourceNTAccounts.Add(id); } else { // // Rare case that we have defined a type of identity reference and not included it in the code logic above. // To avoid this we do not allow IdentityReference to be subclassed outside of the BCL. // Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic."); throw new NotSupportedException(); } } } bool someFailed = false; IdentityReferenceCollection TargetSids = null, TargetNTAccounts = null; if (SourceSidsCount > 0) { TargetSids = SecurityIdentifier.Translate(SourceSids, targetType, out someFailed); if (Homogeneous && !(forceSuccess && someFailed)) { Result = TargetSids; } } if (SourceNTAccountsCount > 0) { TargetNTAccounts = NTAccount.Translate(SourceNTAccounts, targetType, out someFailed); if (Homogeneous && !(forceSuccess && someFailed)) { Result = TargetNTAccounts; } } if (forceSuccess && someFailed) { // // Need to throw an exception here and provide information regarding // which identity references could not be translated to the target type // Result = new IdentityReferenceCollection(); if (TargetSids != null) { foreach (IdentityReference id in TargetSids) { if (id.GetType() != targetType) { Result.Add(id); } } } if (TargetNTAccounts != null) { foreach (IdentityReference id in TargetNTAccounts) { if (id.GetType() != targetType) { Result.Add(id); } } } throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, Result); } else if (!Homogeneous) { SourceSidsCount = 0; SourceNTAccountsCount = 0; Result = new IdentityReferenceCollection(Identities.Count); for (int i = 0; i < Identities.Count; i++) { IdentityReference id = this[i]; Type type = id.GetType(); if (type == targetType) { Result.Add(id); } else if (type == typeof(SecurityIdentifier)) { Result.Add(TargetSids[SourceSidsCount++]); } else if (type == typeof(NTAccount)) { Result.Add(TargetNTAccounts[SourceNTAccountsCount++]); } else { // // Rare case that we have defined a type of identity reference and not included it in the code logic above. // To avoid this we do not allow IdentityReference to be subclassed outside of the BCL. // Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic."); throw new NotSupportedException(); } } } return Result; } #endregion } internal class IdentityReferenceEnumerator : IEnumerator<IdentityReference>, IDisposable { #region Private members // // Current enumeration index // private int _current; // // Parent collection // private readonly IdentityReferenceCollection _collection; #endregion #region Constructors internal IdentityReferenceEnumerator(IdentityReferenceCollection collection) { if (collection == null) { throw new ArgumentNullException("collection"); } Contract.EndContractBlock(); _collection = collection; _current = -1; } #endregion #region IEnumerator implementation /// <internalonly/> object IEnumerator.Current { get { return _collection.Identities[_current]; } } public IdentityReference Current { get { return ((IEnumerator)this).Current as IdentityReference; } } public bool MoveNext() { _current++; return (_current < _collection.Count); } public void Reset() { _current = -1; } public void Dispose() { } #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.IO; using System.Net.Http; using System.Net.Test.Common; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Tests { public partial class HttpWebRequestTest { private const string RequestBody = "This is data to POST."; private readonly byte[] _requestBodyBytes = Encoding.UTF8.GetBytes(RequestBody); private readonly NetworkCredential _explicitCredential = new NetworkCredential("user", "password", "domain"); private HttpWebRequest _savedHttpWebRequest = null; private WebHeaderCollection _savedResponseHeaders = null; private Exception _savedRequestStreamException = null; private Exception _savedResponseException = null; private int _requestStreamCallbackCallCount = 0; private int _responseCallbackCallCount = 0; private readonly ITestOutputHelper _output; public static readonly object[][] EchoServers = System.Net.Test.Common.Configuration.Http.EchoServers; public HttpWebRequestTest(ITestOutputHelper output) { _output = output; } [Theory, MemberData(nameof(EchoServers))] public void Ctor_VerifyDefaults_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Null(request.Accept); Assert.False(request.AllowReadStreamBuffering); Assert.Null(request.ContentType); Assert.Equal(350, request.ContinueTimeout); Assert.Null(request.CookieContainer); Assert.Null(request.Credentials); Assert.False(request.HaveResponse); Assert.NotNull(request.Headers); Assert.Equal(0, request.Headers.Count); Assert.Equal("GET", request.Method); Assert.NotNull(request.Proxy); Assert.Equal(remoteServer, request.RequestUri); Assert.True(request.SupportsCookieContainer); Assert.False(request.UseDefaultCredentials); } [Theory, MemberData(nameof(EchoServers))] public void Ctor_CreateHttpWithString_ExpectNotNull(Uri remoteServer) { string remoteServerString = remoteServer.ToString(); HttpWebRequest request = WebRequest.CreateHttp(remoteServerString); Assert.NotNull(request); } [Theory, MemberData(nameof(EchoServers))] public void Ctor_CreateHttpWithUri_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.NotNull(request); } [Theory, MemberData(nameof(EchoServers))] public void Accept_SetThenGetValidValue_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); string acceptType = "*/*"; request.Accept = acceptType; Assert.Equal(acceptType, request.Accept); } [Theory, MemberData(nameof(EchoServers))] public void Accept_SetThenGetEmptyValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Accept = string.Empty; Assert.Null(request.Accept); } [Theory, MemberData(nameof(EchoServers))] public void Accept_SetThenGetNullValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Accept = null; Assert.Null(request.Accept); } [Theory, MemberData(nameof(EchoServers))] public void AllowReadStreamBuffering_SetFalseThenGet_ExpectFalse(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.AllowReadStreamBuffering = false; Assert.False(request.AllowReadStreamBuffering); } [Theory, MemberData(nameof(EchoServers))] public void AllowReadStreamBuffering_SetTrue_Throws(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Throws<InvalidOperationException>(() => { request.AllowReadStreamBuffering = true; }); } [Theory, MemberData(nameof(EchoServers))] public async Task ContentLength_Get_ExpectSameAsGetResponseStream(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Stream myStream = response.GetResponseStream(); String strContent; using (var sr = new StreamReader(myStream)) { strContent = sr.ReadToEnd(); } long length = response.ContentLength; Assert.Equal(strContent.Length, length); } [Theory, MemberData(nameof(EchoServers))] public void ContentType_SetThenGet_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); string myContent = "application/x-www-form-urlencoded"; request.ContentType = myContent; Assert.Equal(myContent, request.ContentType); } [Theory, MemberData(nameof(EchoServers))] public void ContentType_SetThenGetEmptyValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContentType = string.Empty; Assert.Null(request.ContentType); } [Theory, MemberData(nameof(EchoServers))] public void ContinueTimeout_SetThenGetZero_ExpectZero(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContinueTimeout = 0; Assert.Equal(0, request.ContinueTimeout); } [Theory, MemberData(nameof(EchoServers))] public void ContinueTimeout_SetNegativeOne_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContinueTimeout = -1; } [Theory, MemberData(nameof(EchoServers))] public void ContinueTimeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Throws<ArgumentOutOfRangeException>(() => request.ContinueTimeout = -2); } [Theory, MemberData(nameof(EchoServers))] public void Credentials_SetDefaultCredentialsThenGet_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = CredentialCache.DefaultCredentials; Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials); } [Theory, MemberData(nameof(EchoServers))] public void Credentials_SetExplicitCredentialsThenGet_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; Assert.Equal(_explicitCredential, request.Credentials); } [Theory, MemberData(nameof(EchoServers))] public void UseDefaultCredentials_SetTrue_CredentialsEqualsDefaultCredentials(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; request.UseDefaultCredentials = true; Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials); } [Theory, MemberData(nameof(EchoServers))] public void UseDefaultCredentials_SetFalse_CredentialsNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; request.UseDefaultCredentials = false; Assert.Equal(null, request.Credentials); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetRequestStream_UseGETVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetRequestStream_UseHEADVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Head.Method; Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetRequestStream_UseCONNECTVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = "CONNECT"; Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetRequestStream_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; request.Abort(); WebException ex = Assert.Throws<WebException>(() => request.BeginGetRequestStream(null, null)); Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status); } [Theory, MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] //Test hang forever in desktop. public void BeginGetRequestStream_CreatePostRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.Method = "POST"; IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetRequestStream(null, null); Assert.Throws<InvalidOperationException>(() => { _savedHttpWebRequest.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] //Test hang forever in desktop. public void BeginGetRequestStream_CreateRequestThenBeginGetResponsePrior_ThrowsInvalidOperationException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetResponse(null, null); Assert.Throws<InvalidOperationException>(() => { _savedHttpWebRequest.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] //Test hang forever in desktop. public void BeginGetResponse_CreateRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetResponse(null, null); Assert.Throws<InvalidOperationException>(() => { _savedHttpWebRequest.BeginGetResponse(null, null); }); } [Theory, MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] //Test hang forever in desktop. public void BeginGetResponse_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; request.Abort(); WebException ex = Assert.Throws<WebException>(() => request.BeginGetResponse(null, null)); Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status); } [Theory, MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] //Test hang forever in desktop. public async Task GetRequestStreamAsync_WriteAndDisposeRequestStreamThenOpenRequestStream_ThrowsArgumentException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; Stream requestStream; using (requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } Assert.Throws<ArgumentException>(() => { var sr = new StreamReader(requestStream); }); } [Theory, MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] //Test hang forever in desktop. public async Task GetRequestStreamAsync_SetPOSTThenGet_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; Stream requestStream = await request.GetRequestStreamAsync(); Assert.NotNull(requestStream); } [Theory, MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] //Test hang forever in desktop. public async Task GetResponseAsync_GetResponseStream_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Assert.NotNull(response.GetResponseStream()); } [Theory, MemberData(nameof(EchoServers))] public async Task GetResponseAsync_GetResponseStream_ContainsHost(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Get.Method; WebResponse response = await request.GetResponseAsync(); Stream myStream = response.GetResponseStream(); Assert.NotNull(myStream); String strContent; using (var sr = new StreamReader(myStream)) { strContent = sr.ReadToEnd(); } Assert.True(strContent.Contains("\"Host\": \"" + System.Net.Test.Common.Configuration.Http.Host + "\"")); } [Theory, MemberData(nameof(EchoServers))] public async Task GetResponseAsync_PostRequestStream_ContainsData(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; using (Stream requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } WebResponse response = await request.GetResponseAsync(); Stream myStream = response.GetResponseStream(); String strContent; using (var sr = new StreamReader(myStream)) { strContent = sr.ReadToEnd(); } Assert.True(strContent.Contains(RequestBody)); } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotFedoraOrRedHatOrCentos))] // #16201 [MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] //Test hang forever in desktop. public async Task GetResponseAsync_UseDefaultCredentials_ExpectSuccess(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.UseDefaultCredentials = true; await request.GetResponseAsync(); } [OuterLoop] // fails on networks with DNS servers that provide a dummy page for invalid addresses [Fact] public void GetResponseAsync_ServerNameNotInDns_ThrowsWebException() { string serverUrl = string.Format("http://www.{0}.com/", Guid.NewGuid().ToString()); HttpWebRequest request = WebRequest.CreateHttp(serverUrl); WebException ex = Assert.Throws<WebException>(() => request.GetResponseAsync().GetAwaiter().GetResult()); Assert.Equal(WebExceptionStatus.NameResolutionFailure, ex.Status); } public static object[][] StatusCodeServers = { new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(false, 404) }, new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(true, 404) }, }; [Theory, MemberData(nameof(StatusCodeServers))] public async Task GetResponseAsync_ResourceNotFound_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync()); Assert.Equal(WebExceptionStatus.ProtocolError, ex.Status); } [Theory, MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] //Test hang forever in desktop. public async Task HaveResponse_GetResponseAsync_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Assert.True(request.HaveResponse); } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotFedoraOrRedHatOrCentos))] // #16201 [MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] //Test hang forever in desktop. public async Task Headers_GetResponseHeaders_ContainsExpectedValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync(); String headersString = response.Headers.ToString(); string headersPartialContent = "Content-Type: application/json"; Assert.True(headersString.Contains(headersPartialContent)); } [Theory, MemberData(nameof(EchoServers))] public void Method_SetThenGetToGET_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Get.Method; Assert.Equal(HttpMethod.Get.Method, request.Method); } [Theory, MemberData(nameof(EchoServers))] public void Method_SetThenGetToPOST_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; Assert.Equal(HttpMethod.Post.Method, request.Method); } [Theory, MemberData(nameof(EchoServers))] public void Proxy_GetDefault_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.NotNull(request.Proxy); } [Theory, MemberData(nameof(EchoServers))] public void RequestUri_CreateHttpThenGet_ExpectSameUri(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Equal(remoteServer, request.RequestUri); } [Theory, MemberData(nameof(EchoServers))] public async Task ResponseUri_GetResponseAsync_ExpectSameUri(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Assert.Equal(remoteServer, response.ResponseUri); } [Theory, MemberData(nameof(EchoServers))] public void SupportsCookieContainer_GetDefault_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.True(request.SupportsCookieContainer); } [Theory, MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] //Test hang forever in desktop. public async Task SimpleScenario_UseGETVerb_Success(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); Stream responseStream = response.GetResponseStream(); String responseBody; using (var sr = new StreamReader(responseStream)) { responseBody = sr.ReadToEnd(); } Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Theory, MemberData(nameof(EchoServers))] public async Task SimpleScenario_UsePOSTVerb_Success(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; using (Stream requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); Stream responseStream = response.GetResponseStream(); String responseBody; using (var sr = new StreamReader(responseStream)) { responseBody = sr.ReadToEnd(); } Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Theory, MemberData(nameof(EchoServers))] public async Task ContentType_AddHeaderWithNoContent_SendRequest_HeaderGetsSent(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.ContentType = "application/json"; HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); Stream responseStream = response.GetResponseStream(); String responseBody; using (var sr = new StreamReader(responseStream)) { responseBody = sr.ReadToEnd(); } _output.WriteLine(responseBody); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(responseBody.Contains("Content-Type")); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] [Theory, MemberData(nameof(EchoServers))] public void Abort_BeginGetRequestStreamThenAbort_EndGetRequestStreamThrowsWebException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.Method = "POST"; _savedHttpWebRequest.BeginGetResponse(new AsyncCallback(RequestStreamCallback), null); _savedHttpWebRequest.Abort(); _savedHttpWebRequest = null; WebException wex = _savedRequestStreamException as WebException; Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] [Theory, MemberData(nameof(EchoServers))] public void Abort_BeginGetResponseThenAbort_ResponseCallbackCalledBeforeAbortReturns(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null); _savedHttpWebRequest.Abort(); Assert.Equal(1, _responseCallbackCallCount); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] [Theory, MemberData(nameof(EchoServers))] public void Abort_BeginGetResponseThenAbort_EndGetResponseThrowsWebException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null); _savedHttpWebRequest.Abort(); WebException wex = _savedResponseException as WebException; Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status); } [Theory, MemberData(nameof(EchoServers))] public void Abort_BeginGetResponseUsingNoCallbackThenAbort_Success(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(null, null); _savedHttpWebRequest.Abort(); } [Theory, MemberData(nameof(EchoServers))] public void Abort_CreateRequestThenAbort_Success(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.Abort(); } private void RequestStreamCallback(IAsyncResult asynchronousResult) { _requestStreamCallbackCallCount++; try { Stream stream = (Stream)_savedHttpWebRequest.EndGetRequestStream(asynchronousResult); stream.Dispose(); } catch (Exception ex) { _savedRequestStreamException = ex; } } private void ResponseCallback(IAsyncResult asynchronousResult) { _responseCallbackCallCount++; try { using (HttpWebResponse response = (HttpWebResponse)_savedHttpWebRequest.EndGetResponse(asynchronousResult)) { _savedResponseHeaders = response.Headers; } } catch (Exception ex) { _savedResponseException = ex; } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17842")] [Fact] public void HttpWebRequest_Serialize_Fails() { using (MemoryStream fs = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); var hwr = HttpWebRequest.CreateHttp("http://localhost"); Assert.Throws<PlatformNotSupportedException>(() => formatter.Serialize(fs, hwr)); } } } }
#region License // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Data; using FluentMigrator.Expressions; using FluentMigrator.Infrastructure; using FluentMigrator.Model; namespace FluentMigrator.Builders.Create.Column { public class CreateColumnExpressionBuilder : ExpressionBuilderWithColumnTypesBase<CreateColumnExpression, ICreateColumnOptionSyntax>, ICreateColumnOnTableSyntax, ICreateColumnAsTypeOrInSchemaSyntax, ICreateColumnOptionOrForeignKeyCascadeSyntax { private readonly IMigrationContext _context; public CreateColumnExpressionBuilder(CreateColumnExpression expression, IMigrationContext context) : base(expression) { _context = context; } public ForeignKeyDefinition CurrentForeignKey { get; set; } public ICreateColumnAsTypeOrInSchemaSyntax OnTable(string name) { Expression.TableName = name; return this; } public ICreateColumnAsTypeSyntax InSchema(string schemaName) { Expression.SchemaName = schemaName; return this; } public ICreateColumnOptionSyntax WithDefault(SystemMethods method) { Expression.Column.DefaultValue = method; return this; } public ICreateColumnOptionSyntax WithDefaultValue(object value) { Expression.Column.DefaultValue = value; return this; } public ICreateColumnOptionSyntax WithColumnDescription(string description) { Expression.Column.ColumnDescription = description; return this; } public ICreateColumnOptionSyntax Identity() { Expression.Column.IsIdentity = true; return this; } public ICreateColumnOptionSyntax Indexed() { return Indexed(null); } public ICreateColumnOptionSyntax Indexed(string indexName) { Expression.Column.IsIndexed = true; var index = new CreateIndexExpression { Index = new IndexDefinition { Name = indexName, SchemaName = Expression.SchemaName, TableName = Expression.TableName } }; index.Index.Columns.Add(new IndexColumnDefinition { Name = Expression.Column.Name }); _context.Expressions.Add(index); return this; } public ICreateColumnOptionSyntax PrimaryKey() { Expression.Column.IsPrimaryKey = true; return this; } public ICreateColumnOptionSyntax PrimaryKey(string primaryKeyName) { Expression.Column.IsPrimaryKey = true; Expression.Column.PrimaryKeyName = primaryKeyName; return this; } public ICreateColumnOptionSyntax Nullable() { Expression.Column.IsNullable = true; return this; } public ICreateColumnOptionSyntax NotNullable() { Expression.Column.IsNullable = false; return this; } public ICreateColumnOptionSyntax Unique() { return Unique(null); } public ICreateColumnOptionSyntax Unique(string indexName) { Expression.Column.IsUnique = true; var index = new CreateIndexExpression { Index = new IndexDefinition { Name = indexName, SchemaName = Expression.SchemaName, TableName = Expression.TableName, IsUnique = true } }; index.Index.Columns.Add(new IndexColumnDefinition { Name = Expression.Column.Name }); _context.Expressions.Add(index); return this; } public ICreateColumnOptionOrForeignKeyCascadeSyntax ForeignKey(string primaryTableName, string primaryColumnName) { return ForeignKey(null, null, primaryTableName, primaryColumnName); } public ICreateColumnOptionOrForeignKeyCascadeSyntax ForeignKey(string foreignKeyName, string primaryTableName, string primaryColumnName) { return ForeignKey(foreignKeyName, null, primaryTableName, primaryColumnName); } public ICreateColumnOptionOrForeignKeyCascadeSyntax ForeignKey(string foreignKeyName, string primaryTableSchema, string primaryTableName, string primaryColumnName) { Expression.Column.IsForeignKey = true; var fk = new CreateForeignKeyExpression { ForeignKey = new ForeignKeyDefinition { Name = foreignKeyName, PrimaryTable = primaryTableName, PrimaryTableSchema = primaryTableSchema, ForeignTable = Expression.TableName, ForeignTableSchema = Expression.SchemaName } }; fk.ForeignKey.PrimaryColumns.Add(primaryColumnName); fk.ForeignKey.ForeignColumns.Add(Expression.Column.Name); _context.Expressions.Add(fk); CurrentForeignKey = fk.ForeignKey; return this; } public ICreateColumnOptionOrForeignKeyCascadeSyntax ReferencedBy(string foreignTableName, string foreignColumnName) { return ReferencedBy(null, null, foreignTableName, foreignColumnName); } public ICreateColumnOptionOrForeignKeyCascadeSyntax ReferencedBy(string foreignKeyName, string foreignTableName, string foreignColumnName) { return ReferencedBy(foreignKeyName, null, foreignTableName, foreignColumnName); } public ICreateColumnOptionOrForeignKeyCascadeSyntax ReferencedBy(string foreignKeyName, string foreignTableSchema, string foreignTableName, string foreignColumnName) { var fk = new CreateForeignKeyExpression { ForeignKey = new ForeignKeyDefinition { Name = foreignKeyName, PrimaryTable = Expression.TableName, PrimaryTableSchema = Expression.SchemaName, ForeignTable = foreignTableName, ForeignTableSchema = foreignTableSchema } }; fk.ForeignKey.PrimaryColumns.Add(Expression.Column.Name); fk.ForeignKey.ForeignColumns.Add(foreignColumnName); _context.Expressions.Add(fk); CurrentForeignKey = fk.ForeignKey; return this; } public ICreateColumnOptionOrForeignKeyCascadeSyntax ForeignKey() { Expression.Column.IsForeignKey = true; return this; } [Obsolete("Please use ReferencedBy syntax. This method will be removed in the next version")] public ICreateColumnOptionSyntax References(string foreignKeyName, string foreignTableName, IEnumerable<string> foreignColumnNames) { return References(foreignKeyName, null, foreignTableName, foreignColumnNames); } [Obsolete("Please use ReferencedBy syntax. This method will be removed in the next version")] public ICreateColumnOptionSyntax References(string foreignKeyName, string foreignTableSchema, string foreignTableName, IEnumerable<string> foreignColumnNames) { var fk = new CreateForeignKeyExpression { ForeignKey = new ForeignKeyDefinition { Name = foreignKeyName, PrimaryTable = Expression.TableName, PrimaryTableSchema = Expression.SchemaName, ForeignTable = foreignTableName, ForeignTableSchema = foreignTableSchema } }; fk.ForeignKey.PrimaryColumns.Add(Expression.Column.Name); foreach (var foreignColumnName in foreignColumnNames) fk.ForeignKey.ForeignColumns.Add(foreignColumnName); _context.Expressions.Add(fk); return this; } public ICreateColumnOptionOrForeignKeyCascadeSyntax OnDelete(Rule rule) { CurrentForeignKey.OnDelete = rule; return this; } public ICreateColumnOptionOrForeignKeyCascadeSyntax OnUpdate(Rule rule) { CurrentForeignKey.OnUpdate = rule; return this; } public ICreateColumnOptionSyntax OnDeleteOrUpdate(Rule rule) { OnDelete(rule); OnUpdate(rule); return this; } public override ColumnDefinition GetColumnForType() { return Expression.Column; } } }
using System; using System.Text; using System.Threading; using System.Threading.Tasks; using WebSocket.Portable.Interfaces; using WebSocket.Portable.Internal; using WebSocket.Portable.Tasks; namespace WebSocket.Portable { public abstract class WebSocketClientBase<TWebSocket> : IDisposable, ICanLog where TWebSocket : class, IWebSocket, new() { private readonly string _subProtocol; protected TWebSocket _webSocket; private CancellationTokenSource _cts; private int _maxFrameDataLength = Consts.MaxDefaultFrameDataLength; public event Action Opened; public event Action Closed; public event Action<Exception> Error; public event Action<IWebSocketFrame> FrameReceived; public event Action<IWebSocketMessage> MessageReceived; protected WebSocketClientBase() { this.AutoSendPongResponse = true; } protected WebSocketClientBase(string subProtocol) : this() { _subProtocol = subProtocol; } ~WebSocketClientBase() { this.Dispose(false); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) _webSocket.Dispose(); } /// <summary> /// Gets or sets a value indicating whether to send automatically pong frames when a ping is received. /// </summary> /// <value> /// <c>true</c> if pong frames are send automatically; otherwise, <c>false</c>. /// </value> public bool AutoSendPongResponse { get; set; } /// <summary> /// Gets or sets the maximum length of data to be send in a single frame. If data is to be send is bigger, data will be fragmented. /// </summary> /// <value> /// The maximum length of the frame data. /// </value> /// <exception cref="System.ArgumentOutOfRangeException">value</exception> public int MaxFrameDataLength { get { return _maxFrameDataLength; } set { if (_maxFrameDataLength == value) return; if (value <= 0 || value > Consts.MaxAllowedFrameDataLength) throw new ArgumentOutOfRangeException("value", string.Format("Value must be between 1 and {0}", Consts.MaxAllowedFrameDataLength)); _maxFrameDataLength = value; } } public Task OpenAsync(string uri) { var useSsl = uri.StartsWith("wss"); var port = useSsl ? 443 : 80; return this.OpenAsync(uri, port); } public Task OpenAsync(string uri, int port) { var useSSL = uri.StartsWith("wss"); return this.OpenAsync(uri, port, useSSL); } public Task OpenAsync(string uri, int port, bool useSSL) { return this.OpenAsync(uri, port, useSSL, CancellationToken.None); } public async Task OpenAsync(string uri, int port, bool useSSL, CancellationToken cancellationToken) { if (_webSocket != null) throw new InvalidOperationException("Client has been opened before."); _webSocket = new TWebSocket(); if (!string.IsNullOrEmpty(_subProtocol)) { _webSocket.SetSubProtocol(_subProtocol); } await _webSocket.ConnectAsync(uri, port, useSSL, cancellationToken); await _webSocket.SendHandshakeAsync(cancellationToken); this.ReceiveLoop(); this.OnOpened(); } public Task CloseAsync() { return CloseInternal(); } public Task CloseAsync(CancellationToken cancellationToken) { return CloseInternal(); } private async Task CloseInternal() { if (_cts != null) { _cts.Cancel(); } await Task.Delay(1000); if (_webSocket != null) { await _webSocket.CloseAsync(WebSocketErrorCode.CloseNormal); if (Closed != null) { Closed(); } } } public Task SendAsync(string text) { return this.SendAsync(text, CancellationToken.None); } public Task SendAsync(string text, CancellationToken cancellationToken) { if (text == null) throw new ArgumentNullException("text"); var bytes = Encoding.UTF8.GetBytes(text); return SendAsync(false, bytes, 0, bytes.Length, cancellationToken); } public Task SendAsync(byte[] bytes, int offset, int length) { return SendAsync(bytes, offset, length, CancellationToken.None); } public Task SendAsync(byte[] bytes, int offset, int length, CancellationToken cancellationToken) { return SendAsync(true, bytes, offset, length, cancellationToken); } private Task SendAsync(bool isBinary, byte[] bytes, int offset, int length, CancellationToken cancellationToken) { var task = TaskAsyncHelper.Empty; var max = MaxFrameDataLength; var opcode = isBinary ? WebSocketOpcode.Binary : WebSocketOpcode.Text; while (length > 0) { var size = Math.Min(length, max); length -= size; var frame = new WebSocketClientFrame { Opcode = opcode, IsFin = length == 0, }; frame.Payload = new WebSocketPayload(frame, bytes, offset, size); offset += size; opcode = WebSocketOpcode.Continuation; task = task.Then(f => SendAsync(f, cancellationToken), frame); } return task; } private Task SendAsync(IWebSocketFrame frame, CancellationToken cancellationToken) { return _webSocket.SendFrameAsync(frame, cancellationToken); } protected virtual void OnError(Exception exception) { var handler = Error; if (handler != null) handler(exception); } protected virtual void OnOpened() { var handler = Opened; if (handler != null) handler(); } protected virtual void OnFrameReceived(IWebSocketFrame frame) { var handler = this.FrameReceived; if (handler != null) handler(frame); } protected virtual void OnMessageReceived(IWebSocketMessage message) { var handler = this.MessageReceived; if (handler != null) handler(message); } void IDisposable.Dispose() { Dispose(); } private async void ReceiveLoop() { _cts = new CancellationTokenSource(); WebSocketMessage currentMessage = null; while (!_cts.IsCancellationRequested) { try { var frame = await _webSocket.ReceiveFrameAsync(_cts.Token); if (frame == null) { throw new Exception("null frame"); break; } OnFrameReceived(frame); if (frame.Opcode == WebSocketOpcode.Close) { if (Closed != null) { await CloseAsync(); } break; } if (frame.IsControlFrame) { // Handle ping frame if (frame.Opcode == WebSocketOpcode.Ping && this.AutoSendPongResponse) { var pongFrame = new WebSocketClientFrame { Opcode = WebSocketOpcode.Pong, Payload = frame.Payload }; await SendAsync(pongFrame, _cts.Token); } } else if (frame.IsDataFrame) { if (currentMessage != null) throw new WebSocketException(WebSocketErrorCode.CloseInconstistentData); currentMessage = new WebSocketMessage(); currentMessage.AddFrame(frame); } else if (frame.Opcode == WebSocketOpcode.Continuation) { if (currentMessage == null) throw new WebSocketException(WebSocketErrorCode.CloseInconstistentData); currentMessage.AddFrame(frame); } else { System.Diagnostics.Debug.WriteLine(String.Format("Other frame received: {0}", frame.Opcode)); this.LogDebug("Other frame received: {0}", frame.Opcode); } if (currentMessage != null && currentMessage.IsComplete) { OnMessageReceived(currentMessage); currentMessage = null; } } catch (WebSocketException wsex) { break; } catch (ObjectDisposedException ex) { //https://github.com/rdavisau/sockets-for-pcl/issues/34 break; } catch (TaskCanceledException ex) { break; } catch (Exception ex) { this.LogError("An unexpected error occurred.", ex); this.OnError(ex); break; } } } } }
/* * Copyright 2007 ZXing 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. */ using System; using System.Collections.Generic; using ZXing.Common; namespace ZXing.MicroQrCode.Internal { /// <summary> <p>This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder /// patterns but are smaller and appear at regular intervals throughout the image.</p> /// /// <p>At the moment this only looks for the bottom-right alignment pattern.</p> /// /// <p>This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied, /// pasted and stripped down here for maximum performance but does unfortunately duplicate /// some code.</p> /// /// <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.</p> /// /// </summary> /// <author> Sean Owen /// </author> /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source /// </author> sealed class AlignmentPatternFinder { private readonly BitMatrix image; private readonly IList<AlignmentPattern> possibleCenters; private readonly int startX; private readonly int startY; private readonly int width; private readonly int height; private readonly float moduleSize; private readonly int[] crossCheckStateCount; private readonly ResultPointCallback resultPointCallback; /// <summary> <p>Creates a finder that will look in a portion of the whole image.</p> /// /// </summary> /// <param name="image">image to search /// </param> /// <param name="startX">left column from which to start searching /// </param> /// <param name="startY">top row from which to start searching /// </param> /// <param name="width">width of region to search /// </param> /// <param name="height">height of region to search /// </param> /// <param name="moduleSize">estimated module size so far /// </param> internal AlignmentPatternFinder(BitMatrix image, int startX, int startY, int width, int height, float moduleSize, ResultPointCallback resultPointCallback) { this.image = image; this.possibleCenters = new List<AlignmentPattern>(5); this.startX = startX; this.startY = startY; this.width = width; this.height = height; this.moduleSize = moduleSize; this.crossCheckStateCount = new int[3]; this.resultPointCallback = resultPointCallback; } /// <summary> <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since /// it's pretty performance-critical and so is written to be fast foremost.</p> /// /// </summary> /// <returns> {@link AlignmentPattern} if found /// </returns> internal AlignmentPattern find() { int startX = this.startX; int height = this.height; int maxJ = startX + width; int middleI = startY + (height >> 1); // We are looking for black/white/black modules in 1:1:1 ratio; // this tracks the number of black/white/black modules seen so far int[] stateCount = new int[3]; for (int iGen = 0; iGen < height; iGen++) { // Search from middle outwards int i = middleI + ((iGen & 0x01) == 0 ? ((iGen + 1) >> 1) : -((iGen + 1) >> 1)); stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; int j = startX; // Burn off leading white pixels before anything else; if we start in the middle of // a white run, it doesn't make sense to count its length, since we don't know if the // white run continued to the left of the start point while (j < maxJ && !image[j, i]) { j++; } int currentState = 0; while (j < maxJ) { if (image[j, i]) { // Black pixel if (currentState == 1) { // Counting black pixels stateCount[1]++; } else { // Counting white pixels if (currentState == 2) { // A winner? if (foundPatternCross(stateCount)) { // Yes AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j); if (confirmed != null) { return confirmed; } } stateCount[0] = stateCount[2]; stateCount[1] = 1; stateCount[2] = 0; currentState = 1; } else { stateCount[++currentState]++; } } } else { // White pixel if (currentState == 1) { // Counting black pixels currentState++; } stateCount[currentState]++; } j++; } if (foundPatternCross(stateCount)) { AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, maxJ); if (confirmed != null) { return confirmed; } } } // Hmm, nothing we saw was observed and confirmed twice. If we had // any guess at all, return it. if (possibleCenters.Count != 0) { return possibleCenters[0]; } return null; } /// <summary> Given a count of black/white/black pixels just seen and an end position, /// figures the location of the center of this black/white/black run. /// </summary> private static float? centerFromEnd(int[] stateCount, int end) { var result = (end - stateCount[2]) - stateCount[1] / 2.0f; if (Single.IsNaN(result)) return null; return result; } /// <param name="stateCount">count of black/white/black pixels just read /// </param> /// <returns> true iff the proportions of the counts is close enough to the 1/1/1 ratios /// used by alignment patterns to be considered a match /// </returns> private bool foundPatternCross(int[] stateCount) { float maxVariance = moduleSize / 2.0f; for (int i = 0; i < 3; i++) { if (Math.Abs(moduleSize - stateCount[i]) >= maxVariance) { return false; } } return true; } /// <summary> /// <p>After a horizontal scan finds a potential alignment pattern, this method /// "cross-checks" by scanning down vertically through the center of the possible /// alignment pattern to see if the same proportion is detected.</p> /// </summary> /// <param name="startI">row where an alignment pattern was detected</param> /// <param name="centerJ">center of the section that appears to cross an alignment pattern</param> /// <param name="maxCount">maximum reasonable number of modules that should be /// observed in any reading state, based on the results of the horizontal scan</param> /// <param name="originalStateCountTotal">The original state count total.</param> /// <returns> /// vertical center of alignment pattern, or null if not found /// </returns> private float? crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) { int maxI = image.Height; int[] stateCount = crossCheckStateCount; stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; // Start counting up from center int i = startI; while (i >= 0 && image[centerJ, i] && stateCount[1] <= maxCount) { stateCount[1]++; i--; } // If already too many modules in this state or ran off the edge: if (i < 0 || stateCount[1] > maxCount) { return null; } while (i >= 0 && !image[centerJ, i] && stateCount[0] <= maxCount) { stateCount[0]++; i--; } if (stateCount[0] > maxCount) { return null; } // Now also count down from center i = startI + 1; while (i < maxI && image[centerJ, i] && stateCount[1] <= maxCount) { stateCount[1]++; i++; } if (i == maxI || stateCount[1] > maxCount) { return null; } while (i < maxI && !image[centerJ, i] && stateCount[2] <= maxCount) { stateCount[2]++; i++; } if (stateCount[2] > maxCount) { return null; } int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) { return null; } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : null; } /// <summary> <p>This is called when a horizontal scan finds a possible alignment pattern. It will /// cross check with a vertical scan, and if successful, will see if this pattern had been /// found on a previous horizontal scan. If so, we consider it confirmed and conclude we have /// found the alignment pattern.</p> /// /// </summary> /// <param name="stateCount">reading state module counts from horizontal scan /// </param> /// <param name="i">row where alignment pattern may be found /// </param> /// <param name="j">end of possible alignment pattern in row /// </param> /// <returns> {@link AlignmentPattern} if we have found the same pattern twice, or null if not /// </returns> private AlignmentPattern handlePossibleCenter(int[] stateCount, int i, int j) { int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; float? centerJ = centerFromEnd(stateCount, j); if (centerJ == null) return null; float? centerI = crossCheckVertical(i, (int)centerJ, 2 * stateCount[1], stateCountTotal); if (centerI != null) { float estimatedModuleSize = (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f; foreach (var center in possibleCenters) { // Look for about the same center and module size: if (center.aboutEquals(estimatedModuleSize, centerI.Value, centerJ.Value)) { return center.combineEstimate(centerI.Value, centerJ.Value, estimatedModuleSize); } } // Hadn't found this before; save it var point = new AlignmentPattern(centerJ.Value, centerI.Value, estimatedModuleSize); possibleCenters.Add(point); if (resultPointCallback != null) { resultPointCallback(point); } } return null; } } }
/* | Version 10.1.1 | Copyright 2012 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using Esri_Telecom_Tools.Core; using Esri_Telecom_Tools.Core.Utils; using ESRI.ArcGIS.Editor; using System.Windows.Forms; namespace Esri_Telecom_Tools.Helpers { /// <summary> /// This class does all the real work so that we can /// change the UI more easily if necessary /// </summary> public class FiberCableConfigHelper : EditorBase { private LogHelper _logHelper = LogHelper.Instance(); private HookHelperExt _hookHelper = null; // The current fiber cable configuration being used. private FiberCableConfiguration _fiberConfig = null; public FiberCableConfigHelper(HookHelperExt hookHelper, ESRI.ArcGIS.Editor.IEditor3 editor) : base(editor) { _hookHelper = hookHelper; } public FiberCableConfiguration FiberCableConfig { set { _fiberConfig = value; } } protected override void editor_OnCreateFeature(ESRI.ArcGIS.Geodatabase.IObject obj) { // Check for bad inputs ESRI.ArcGIS.Geodatabase.IFeature feature = obj as ESRI.ArcGIS.Geodatabase.IFeature; if (feature == null || feature.Class == null) return; // Work out type of feature ESRI.ArcGIS.Geodatabase.IDataset dataset = (ESRI.ArcGIS.Geodatabase.IDataset)feature.Class; string tableName = GdbUtils.ParseTableName(dataset); // ----------------------------- // Fiber // ----------------------------- if (0 == string.Compare(ConfigUtil.FiberCableFtClassName, tableName, true)) { try { //FiberCableConfiguration cf = // ConfigUtil.FiberCableConfigurationFromDisplayName(listView1.SelectedItems[0].Text); if (_fiberConfig != null) { ConfigureCable(feature, _fiberConfig, true); } } catch (Exception ex) { _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "Failed to configure cable.", ex.Message); string message = "Failed to configure cable:" + System.Environment.NewLine + ex.Message; MessageBox.Show(message, "Configure Fiber Cable", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } protected override void editor_OnChangeFeature(ESRI.ArcGIS.Geodatabase.IObject obj) { // throw new NotImplementedException(); } protected override void editor_OnDeleteFeature(ESRI.ArcGIS.Geodatabase.IObject obj) { // throw new NotImplementedException(); } protected override void editor_OnSelectionChanged() { // throw new NotImplementedException(); } /// <summary> /// Sets the buffer tube and strand counts based on the given configuration. If IPID and/or CABLEID are null, it also /// takes care of them /// </summary> /// <param name="feature">The FiberCable feature to configure</param> /// <param name="configuration">The tube/strand counts</param> /// <param name="isExistingOperation">Flag to control whether this method is being called from within an existing /// edit operation</param> /// <returns>Success</returns> protected bool ConfigureCable(ESRI.ArcGIS.Geodatabase.IFeature feature, FiberCableConfiguration configuration, bool isExistingOperation) { bool isComplete = false; bool isOurOperationOpen = false; // The following assignments are defaults for the case where they are not already populated on the feature string fiberCableIpid = Guid.NewGuid().ToString("B").ToUpper(); // The following will be set during Validation ESRI.ArcGIS.Geodatabase.IObjectClass ftClass = null; ESRI.ArcGIS.Geodatabase.IFields fields = null; int ipidIdx = -1; int bufferCountIdx = -1; int strandCountIdx = -1; #region Validation if (null == feature) { throw new ArgumentNullException("feature"); } if (null == configuration) { throw new ArgumentNullException("configuration"); } if (_editor.EditState == ESRI.ArcGIS.Editor.esriEditState.esriStateNotEditing) { throw new InvalidOperationException("You must be editing the workspace to perform this operation."); } ftClass = feature.Class; fields = ftClass.Fields; string missingFieldFormat = "Field {0} is missing."; ipidIdx = fields.FindField(ConfigUtil.IpidFieldName); if (-1 == ipidIdx) { throw new InvalidOperationException(string.Format(missingFieldFormat, ConfigUtil.IpidFieldName)); } bufferCountIdx = fields.FindField(ConfigUtil.NumberOfBuffersFieldName); if (-1 == bufferCountIdx) { throw new InvalidOperationException(string.Format(missingFieldFormat, ConfigUtil.NumberOfBuffersFieldName)); } strandCountIdx = fields.FindField(ConfigUtil.NumberOfFibersFieldName); if (-1 == strandCountIdx) { throw new InvalidOperationException(string.Format(missingFieldFormat, ConfigUtil.NumberOfFibersFieldName)); } #endregion ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass(); ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = _hookHelper.CreateProgressDialog(trackCancel, "Preparing to configure cable...", 1, configuration.TotalFiberCount, 1, "Starting edit operation...", "Fiber Configuration"); ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = (ESRI.ArcGIS.esriSystem.IStepProgressor)progressDialog; progressDialog.ShowDialog(); stepProgressor.Step(); if (!isExistingOperation) { _editor.StartOperation(); isOurOperationOpen = true; } try { if (DBNull.Value == feature.get_Value(ipidIdx)) { feature.set_Value(ipidIdx, fiberCableIpid); } else { fiberCableIpid = feature.get_Value(ipidIdx).ToString(); } feature.set_Value(bufferCountIdx, configuration.BufferCount); feature.set_Value(strandCountIdx, configuration.FibersPerTube); isComplete = GenerateUnits(feature, configuration, progressDialog, trackCancel); progressDialog.Description = "Completing configuration..."; stepProgressor.Step(); if (isOurOperationOpen) { if (isComplete) { feature.Store(); _editor.StopOperation("Configure Fiber"); } else { _editor.AbortOperation(); } } } catch(Exception e) { if (isOurOperationOpen) { _editor.AbortOperation(); } } progressDialog.HideDialog(); return isComplete; } /* private String fiberOrBufferColorLookup(int number) { switch (number) { case 1: return "Blue"; case 2: return "Orange"; case 3: return "Green"; case 4: return "Brown"; case 5: return "Slate"; case 6: return "White"; case 7: return "Red"; case 8: return "Black"; case 9: return "Yellow"; case 10: return "Violet"; case 11: return "Rose"; case 12: return "Aqua"; default: return string.Empty; } } */ /// <summary> /// Generates a number of buffer tubes and fiber records for a fiber cable, given a configuration. /// </summary> /// <param name="feature">IFeature to generate for</param> /// <param name="configuration">Specification of buffer and fiber counts</param> /// <param name="progressDialog">Progress dialog for user notification</param> /// <param name="trackCancel">TrackCancel used in the progress dialog</param> /// <returns>Success</returns> private bool GenerateUnits(ESRI.ArcGIS.Geodatabase.IFeature feature, FiberCableConfiguration configuration, ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog, ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel) { bool isComplete = false; bool isCancelled = false; Guid g; ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = (ESRI.ArcGIS.esriSystem.IStepProgressor)progressDialog; ESRI.ArcGIS.Geodatabase.IObjectClass ftClass = feature.Class; using (ESRI.ArcGIS.ADF.ComReleaser releaser = new ESRI.ArcGIS.ADF.ComReleaser()) { ESRI.ArcGIS.Geodatabase.IRelationshipClass cableHasBuffer = GdbUtils.GetRelationshipClass(ftClass, ConfigUtil.FiberCableToBufferRelClassName); releaser.ManageLifetime(cableHasBuffer); ESRI.ArcGIS.Geodatabase.IRelationshipClass cableHasFiber = GdbUtils.GetRelationshipClass(ftClass, ConfigUtil.FiberCableToFiberRelClassName); releaser.ManageLifetime(cableHasFiber); ESRI.ArcGIS.Geodatabase.IRelationshipClass bufferHasFiber = GdbUtils.GetRelationshipClass(ftClass, ConfigUtil.BufferToFiberRelClassName); releaser.ManageLifetime(bufferHasFiber); ESRI.ArcGIS.Geodatabase.ITable bufferTable = cableHasBuffer.DestinationClass as ESRI.ArcGIS.Geodatabase.ITable; ESRI.ArcGIS.Geodatabase.ITable fiberTable = cableHasFiber.DestinationClass as ESRI.ArcGIS.Geodatabase.ITable; // Fields to populate on buffer int bufferIpidIdx = bufferTable.Fields.FindField(ConfigUtil.IpidFieldName); int fiberCountIdx = bufferTable.Fields.FindField(ConfigUtil.NumberOfFibersFieldName); int bufferToCableIdx = bufferTable.Fields.FindField(cableHasBuffer.OriginForeignKey); object bufferToCableValue = feature.get_Value(feature.Fields.FindField(cableHasBuffer.OriginPrimaryKey)); // Fields to populate on fiber int fiberIpidIdx = fiberTable.Fields.FindField(ConfigUtil.IpidFieldName); int fiberNumberIdx = fiberTable.Fields.FindField(ConfigUtil.Fiber_NumberFieldName); int fiberColorIdx = fiberTable.Fields.FindField(ConfigUtil.Fiber_ColorFieldName); int fiberToCableIdx = fiberTable.Fields.FindField(cableHasFiber.OriginForeignKey); object fiberToCableValue = feature.get_Value(feature.Fields.FindField(cableHasFiber.OriginPrimaryKey)); int fiberToBufferIdx = fiberTable.Fields.FindField(bufferHasFiber.OriginForeignKey); int fiberToBufferValueIdx = bufferTable.Fields.FindField(bufferHasFiber.OriginPrimaryKey); // Research using InsertCursor for speed. int fiberNumber = 0; for (int bufferIdx = 1; bufferIdx <= configuration.BufferCount; bufferIdx++) { g = Guid.NewGuid(); string bufferId = g.ToString("B").ToUpper(); ESRI.ArcGIS.Geodatabase.IRow row = bufferTable.CreateRow(); releaser.ManageLifetime(row); row.set_Value(bufferIpidIdx, bufferId); row.set_Value(fiberCountIdx, configuration.FibersPerTube); row.set_Value(bufferToCableIdx, bufferToCableValue); row.Store(); object fiberToBufferValue = row.get_Value(fiberToBufferValueIdx); // Research using InsertCursor for speed. for (int fiberIdx = 1; fiberIdx <= configuration.FibersPerTube; fiberIdx++) { fiberNumber++; progressDialog.Description = string.Format("Creating fiber {0} of {1}", fiberNumber, configuration.TotalFiberCount); stepProgressor.Step(); g = Guid.NewGuid(); ESRI.ArcGIS.Geodatabase.IRow fiberRow = fiberTable.CreateRow(); releaser.ManageLifetime(fiberRow); fiberRow.set_Value(fiberIpidIdx, g.ToString("B").ToUpper()); fiberRow.set_Value(fiberNumberIdx, fiberNumber); // Dangerous if coded values are altered but while // domain type is int Rather than string coded, this // is quickest way to add this // Dont do for fiber groupings of more than 12 if (configuration.FibersPerTube <= 12) fiberRow.set_Value(fiberColorIdx, fiberIdx); fiberRow.set_Value(fiberToBufferIdx, fiberToBufferValue); fiberRow.set_Value(fiberToCableIdx, fiberToCableValue); fiberRow.Store(); if (!trackCancel.Continue()) { isCancelled = true; break; } } if (!trackCancel.Continue()) { isCancelled = true; break; } } if (!isCancelled) { isComplete = true; } } return isComplete; } } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Runtime.InteropServices; using SharpDX.DXGI; namespace SharpDX.Toolkit.Graphics { /// <summary> /// PixelFormat is equivalent to <see cref="SharpDX.DXGI.Format"/>. /// </summary> /// <remarks> /// This structure is implicitly castable to and from <see cref="SharpDX.DXGI.Format"/>, you can use it inplace where <see cref="SharpDX.DXGI.Format"/> is required /// and vice-versa. /// Usage is slightly different from <see cref="SharpDX.DXGI.Format"/>, as you have to select the type of the pixel format first (<see cref="Typeless"/>, <see cref="SInt"/>...etc) /// and then access the available pixel formats for this type. Example: PixelFormat.UNorm.R8. /// </remarks> /// <msdn-id>bb173059</msdn-id> /// <unmanaged>DXGI_FORMAT</unmanaged> /// <unmanaged-short>DXGI_FORMAT</unmanaged-short> [StructLayout(LayoutKind.Sequential, Size = 4)] public struct PixelFormat : IEquatable<PixelFormat> { /// <summary> /// Gets the value as a <see cref="SharpDX.DXGI.Format"/> enum. /// </summary> public readonly Format Value; /// <summary> /// Internal constructor. /// </summary> /// <param name="format"></param> private PixelFormat(Format format) { this.Value = format; } public int SizeInBytes { get { return (int)FormatHelper.SizeOfInBytes(this); } } public static readonly PixelFormat Unknown = new PixelFormat(Format.Unknown); public static class A8 { #region Constants and Fields public static readonly PixelFormat UNorm = new PixelFormat(Format.A8_UNorm); #endregion } public static class B5G5R5A1 { #region Constants and Fields public static readonly PixelFormat UNorm = new PixelFormat(Format.B5G5R5A1_UNorm); #endregion } public static class B5G6R5 { #region Constants and Fields public static readonly PixelFormat UNorm = new PixelFormat(Format.B5G6R5_UNorm); #endregion } public static class B8G8R8A8 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.B8G8R8A8_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.B8G8R8A8_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.B8G8R8A8_UNorm_SRgb); #endregion } public static class B8G8R8X8 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.B8G8R8X8_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.B8G8R8X8_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.B8G8R8X8_UNorm_SRgb); #endregion } public static class BC1 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.BC1_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.BC1_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.BC1_UNorm_SRgb); #endregion } public static class BC2 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.BC2_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.BC2_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.BC2_UNorm_SRgb); #endregion } public static class BC3 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.BC3_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.BC3_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.BC3_UNorm_SRgb); #endregion } public static class BC4 { #region Constants and Fields public static readonly PixelFormat SNorm = new PixelFormat(Format.BC4_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.BC4_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.BC4_UNorm); #endregion } public static class BC5 { #region Constants and Fields public static readonly PixelFormat SNorm = new PixelFormat(Format.BC5_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.BC5_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.BC5_UNorm); #endregion } public static class BC6H { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.BC6H_Typeless); #endregion } public static class BC7 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.BC7_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.BC7_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.BC7_UNorm_SRgb); #endregion } public static class R10G10B10A2 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.R10G10B10A2_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R10G10B10A2_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R10G10B10A2_UNorm); #endregion } public static class R11G11B10 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R11G11B10_Float); #endregion } public static class R16 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R16_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R16_SInt); public static readonly PixelFormat SNorm = new PixelFormat(Format.R16_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.R16_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R16_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R16_UNorm); #endregion } public static class R16G16 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R16G16_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R16G16_SInt); public static readonly PixelFormat SNorm = new PixelFormat(Format.R16G16_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.R16G16_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R16G16_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R16G16_UNorm); #endregion } public static class R16G16B16A16 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R16G16B16A16_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R16G16B16A16_SInt); public static readonly PixelFormat SNorm = new PixelFormat(Format.R16G16B16A16_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.R16G16B16A16_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R16G16B16A16_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R16G16B16A16_UNorm); #endregion } public static class R32 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R32_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R32_SInt); public static readonly PixelFormat Typeless = new PixelFormat(Format.R32_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R32_UInt); #endregion } public static class R32G32 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R32G32_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R32G32_SInt); public static readonly PixelFormat Typeless = new PixelFormat(Format.R32G32_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R32G32_UInt); #endregion } public static class R32G32B32 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R32G32B32_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R32G32B32_SInt); public static readonly PixelFormat Typeless = new PixelFormat(Format.R32G32B32_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R32G32B32_UInt); #endregion } public static class R32G32B32A32 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R32G32B32A32_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R32G32B32A32_SInt); public static readonly PixelFormat Typeless = new PixelFormat(Format.R32G32B32A32_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R32G32B32A32_UInt); #endregion } public static class R8 { #region Constants and Fields public static readonly PixelFormat SInt = new PixelFormat(Format.R8_SInt); public static readonly PixelFormat SNorm = new PixelFormat(Format.R8_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.R8_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R8_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R8_UNorm); #endregion } public static class R8G8 { #region Constants and Fields public static readonly PixelFormat SInt = new PixelFormat(Format.R8G8_SInt); public static readonly PixelFormat SNorm = new PixelFormat(Format.R8G8_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.R8G8_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R8G8_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R8G8_UNorm); #endregion } public static class R8G8B8A8 { #region Constants and Fields public static readonly PixelFormat SInt = new PixelFormat(Format.R8G8B8A8_SInt); public static readonly PixelFormat SNorm = new PixelFormat(Format.R8G8B8A8_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.R8G8B8A8_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R8G8B8A8_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R8G8B8A8_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.R8G8B8A8_UNorm_SRgb); #endregion } public static implicit operator Format(PixelFormat from) { return from.Value; } public static implicit operator PixelFormat(Format from) { return new PixelFormat(from); } public bool Equals(PixelFormat other) { return Value.Equals(other.Value); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is PixelFormat && Equals((PixelFormat) obj); } public override int GetHashCode() { return Value.GetHashCode(); } public static bool operator ==(PixelFormat left, PixelFormat right) { return left.Equals(right); } public static bool operator !=(PixelFormat left, PixelFormat right) { return !left.Equals(right); } public override string ToString() { return string.Format("{0}", Value); } } }
using CapnpNet.Rpc; using System; using System.Runtime.CompilerServices; namespace CapnpNet { /// <summary> /// Implementors must be a struct whose only field is <see cref="Struct"/>. /// </summary> public interface IStruct : IAbsPointer // TODO: rename to IPureStruct { Struct Struct { get; } } public static class StructExtensions { public static T As<T>(this Struct s) where T : struct, IStruct => Unsafe.As<Struct, T>(ref s); public static Struct GetStruct<T>(this T structObj) where T : struct, IStruct => structObj.Struct; public static bool Compact<T>(this T structObj, bool dataOnly = true) where T : struct, IStruct { var s = structObj.Struct; if (s.IsPartialStruct) { return false; } var originalEnd = s.StructWordOffset + s.DataWords + s.PointerWords; int savedWords = 0; var dw = s.DataWords; while (dw > 0 && s.ReadInt64(dw - 1) == 0) { dw--; savedWords++; } var pw = s.PointerWords; if (dataOnly == false) { while (pw > 0 && s.ReadRawPointer(pw - 1).RawValue == 0) { pw--; savedWords++; } } if (savedWords == 0) return false; var newStruct = new Struct(s.Segment, s.StructWordOffset, dw, pw); var pointerShift = s.DataWords - dw; if (pointerShift > 0) { // need to shift pointers over for (int i = 0; i < pw; i++) { var ptr = s.ReadRawPointer(i); if (ptr.Type == PointerType.Struct || ptr.Type == PointerType.List) ptr.WordOffset += pointerShift; newStruct.WriteRawPointer(i, ptr); } } var seg = s.Segment; for (int i = 0; i < savedWords; i++) { seg.GetWord(originalEnd - i - 1) = 0; } Unsafe.As<T, Struct>(ref structObj) = newStruct; seg.TryReclaim(originalEnd, savedWords); return true; } public static T CopyTo<T>(this T structObj, Message dest) where T : struct, IStruct { var s = structObj.Struct.CopyTo(dest); return Unsafe.As<Struct, T>(ref s); } } public readonly struct Struct : IStruct { private readonly Segment _segment; private readonly int _structWordOffset; // in the encoding spec, technically this is a uint, but currently I bottom out at an API that uses int :( private readonly ushort _dataWords, _pointerWords; private readonly sbyte _upgradedListElementByteOffset; public static bool operator ==(Struct a, Struct b) { return a._segment == b._segment && a._structWordOffset == b._structWordOffset && a._dataWords == b._dataWords && a._pointerWords == b._pointerWords && a._upgradedListElementByteOffset == b._upgradedListElementByteOffset; } public static bool operator !=(Struct a, Struct b) => !(a == b); public override bool Equals(object obj) => obj is Struct s && this == s; public override int GetHashCode() { return _segment.GetHashCode() * 17 + _structWordOffset; } public Struct(Segment segment, int pointerOffset, StructPointer pointer) : this( segment, pointerOffset + pointer.WordOffset, pointer.DataWords, pointer.PointerWords) { } public Struct(Segment segment, int structWordOffset, ushort dataWords, ushort pointerWords, sbyte upgradedListElementSize = -1) { _segment = segment; _structWordOffset = structWordOffset; _dataWords = dataWords; _pointerWords = pointerWords; _upgradedListElementByteOffset = upgradedListElementSize; } Struct IStruct.Struct => this; public AbsPointer Pointer => new AbsPointer(_segment, 0, new StructPointer() { Type = PointerType.Struct, WordOffset = _structWordOffset, DataWords = _dataWords, PointerWords = _pointerWords }); public Pointer[] PointersDebug { get { var ret = new Pointer[_pointerWords]; ref var pointers = ref Unsafe.As<ulong, Pointer>(ref _segment.GetWord(_structWordOffset + _dataWords)); for (int i = 0; i < _pointerWords; i++) { ret[i] = Unsafe.Add(ref pointers, i); } return ret; } } #if SPAN // <summary> // Note, when _upgradedListElementOffset > 0, Span will be one word long, and may comprise of multiple structs. // </summary> public Span<ulong> Span => _segment.Span.Slice((int)_structWordOffset, _dataWords + _pointerWords); #endif public int StructWordOffset => _structWordOffset; public Segment Segment => _segment; public ushort DataWords => _dataWords; public ushort PointerWords => _pointerWords; public bool IsEmpty => _dataWords == 0 && _pointerWords == 0; public bool IsPartialStruct => _upgradedListElementByteOffset != -1; public override string ToString() => $"Struct(S={_segment.SegmentIndex}, O={_structWordOffset}, DW={_dataWords}, PW={_pointerWords})"; public int CalculateSize() { // TODO: traversal depth limit var size = this.DataWords + this.PointerWords; for (int i = 0; i < this.PointerWords; i++) { var ptr = this.ReadRawPointer(i); var dataSeg = _segment; var srcMsg = _segment.Message; // TODO: only dereference far; don't count against transversal limit srcMsg.Traverse(ref ptr, ref dataSeg, out int baseOffset); if (ptr.Type == PointerType.Struct) { size += this.DereferencePointer<Struct>(i).CalculateSize(); } else if (ptr.Is(out ListPointer list)) { int elementsPerWord; if (list.ElementSize == ElementSize.OneBit) elementsPerWord = 64; else if (list.ElementSize == ElementSize.OneByte) elementsPerWord = 8; else if (list.ElementSize == ElementSize.TwoBytes) elementsPerWord = 4; else if (list.ElementSize == ElementSize.FourBytes) elementsPerWord = 2; else if (list.ElementSize >= ElementSize.EightBytesNonPointer) elementsPerWord = 1; else throw new NotSupportedException(); var words = ((int)list.ElementCount + elementsPerWord - 1) / elementsPerWord; if (list.ElementSize == ElementSize.Composite) words++; size += words; } } return size; } public Struct CopyTo(Message dest) { if (this.IsEmpty) return default; if (this.Segment.Message == dest) return this; var newS = dest.Allocate(this.DataWords, this.PointerWords); var destSeg = newS.Segment; var srcSeg = this.Segment; var srcMsg = srcSeg.Message; // copy data ref ulong src = ref srcSeg.GetWord(this.StructWordOffset); ref ulong dst = ref destSeg.GetWord(newS.StructWordOffset); for (int i = 0; i < this.DataWords; i++) { Unsafe.Add(ref dst, i) = Unsafe.Add(ref src, i); } int srcPointerBase = _structWordOffset + _dataWords + 1; int dstPointerBase = newS.StructWordOffset + newS.DataWords + 1; for (int i = 0; i < this.PointerWords; i++) { Unsafe.Add(ref dst, _dataWords + i) = new AbsPointer(_segment, srcPointerBase + i, this.GetPointer(i)) .CopyTo(dest) .ToPointer(destSeg, dstPointerBase + i) .RawValue; } return newS; } private ref Pointer GetPointer(int index) { Check.Range(index, _pointerWords); return ref Unsafe.As<ulong, Pointer>(ref _segment.GetWord(_structWordOffset + _dataWords + index)); } #region Read methods public Pointer ReadRawPointer(int pointerIndex) { Check.NonNegative(pointerIndex); // TODO: how to handle default? if (pointerIndex >= this.PointerWords) return new Pointer(); return this.GetPointer(pointerIndex); } public T DereferencePointer<T>(int pointerIndex) where T : IAbsPointer { if (this.DereferenceCore(pointerIndex, out var pointer, out var baseOffset, out var targetSegment)) { if (typeof(T) == typeof(ICapability) || ReflectionCache<T>.ImplementsICapability) { // TODO: handle default Check.IsTrue(pointer.Type == PointerType.Other && pointer.OtherPointerType == OtherPointerType.Capability); ref var capEntry = ref this.Segment.Message.LocalCaps.TryGet(pointer.CapabilityId, out var found); if (found == false) { // TODO: how to handle missing cap? throw new NotImplementedException(); } return (T)capEntry.Capability; } var p = new AbsPointer(targetSegment, baseOffset, pointer); if (ReflectionCache<T>.ImplementsIPureAbsPointer) { // TODO: grab expected pointer type(s) from reflection cache // - or, to put a Verify method on IAbsPointer; FlatArray's verifications is complicated. return Unsafe.As<AbsPointer, T>(ref p); } else if (ReflectionCache<T>.ImplementsIStruct) // pure struct { if (p.IsStruct(out var s) == false) { throw new InvalidOperationException($"Pointer type {p.Tag.Type} is not Struct"); } return Unsafe.As<Struct, T>(ref s); } throw new InvalidOperationException($"{typeof(T).Name} expected to implement either IPureStruct or IPureAbsPointer"); } // TODO: how to handle default? return default; } // TODO: replace with AbsPointer private bool DereferenceCore(int pointerIndex, out Pointer pointer, out int baseOffset, out Segment targetSegment) { Check.NonNegative(pointerIndex); if (pointerIndex >= this.PointerWords) { pointer = default; baseOffset = 0; targetSegment = null; return false; } pointer = this.GetPointer(pointerIndex); if (pointer == default) { baseOffset = 0; targetSegment = null; return false; } targetSegment = _segment; if (!_segment.Message.Traverse(ref pointer, ref targetSegment, out baseOffset)) { baseOffset = _structWordOffset + _dataWords + pointerIndex + 1; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private T GetOrDefault<T>(int index) where T : struct { Check.NonNegative(index); if (_upgradedListElementByteOffset >= 0) { // this is a list element upgraded to a struct; only the first field is present if (index > 0) return default; return Unsafe.As<byte, T>(ref _segment.GetByte(_structWordOffset * sizeof(ulong) + _upgradedListElementByteOffset / Unsafe.SizeOf<T>())); } else { if (index * Unsafe.SizeOf<T>() >= _dataWords * sizeof(ulong)) return default; return Unsafe.As<byte, T>(ref _segment.GetByte(_structWordOffset * sizeof(ulong) + index * Unsafe.SizeOf<T>())); } } // TODO: option which throws instead of return default for out of range? // TODO: aggressiveinlining attribute? Also, if inlined, does defaultValue = 0 get optimized away? // TODO: take a second look at these xor operations for the smaller integers public sbyte ReadInt8(int index, sbyte defaultValue = 0) => (sbyte)(this.GetOrDefault<sbyte>(index) ^ defaultValue); public byte ReadUInt8(int index, byte defaultValue = 0) => (byte)(this.GetOrDefault<byte>(index) ^ defaultValue); public short ReadInt16(int index, short defaultValue = 0) => (short)(this.GetOrDefault<short>(index) ^ defaultValue); public ushort ReadUInt16(int index, ushort defaultValue = 0) => (ushort)(this.GetOrDefault<ushort>(index) ^ defaultValue); public int ReadInt32(int index, int defaultValue = 0) => this.GetOrDefault<int>(index) ^ defaultValue; public uint ReadUInt32(int index, uint defaultValue = 0) => this.GetOrDefault<uint>(index) ^ defaultValue; public long ReadInt64(int index, long defaultValue = 0) => this.GetOrDefault<long>(index) ^ defaultValue; public ulong ReadUInt64(int index, ulong defaultValue = 0) => this.GetOrDefault<ulong>(index) ^ defaultValue; public float ReadFloat32(int index, float defaultValue = 0) => TypeHelpers.Xor(this.GetOrDefault<float>(index), defaultValue); public double ReadFloat64(int index, double defaultValue = 0) => TypeHelpers.Xor(this.GetOrDefault<double>(index), defaultValue); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ReadBool(int index, bool defaultValue = false) { // bool list elements can't be upgraded to struct if (_upgradedListElementByteOffset >= 0) return defaultValue; var wordIndex = index >> 6; if (wordIndex >= this.DataWords) return defaultValue; // TODO: byte-sized mask? var mask = 1UL << (index & 63); return (_segment.GetWord(_structWordOffset + wordIndex) & mask) > 0 != defaultValue; } #endregion Read methods #region Write methods public void WriteRawPointer(int pointerIndex, Pointer pointer) { // TODO: disallow writing arbitrary capability pointers if (pointerIndex < 0 || pointerIndex >= this.PointerWords) { throw new ArgumentOutOfRangeException("pointerIndex", "Pointer index out of range"); } this.GetPointer(pointerIndex) = pointer; } public void WritePointer<T>(int pointerIndex, T dest) where T : IAbsPointer { var p = dest.Pointer; this.WritePointerCore( pointerIndex, p.Segment, p.DataOffset, p.Tag); } public void WritePointer(int pointerIndex, ICapability cap) { Check.NotNull(cap, nameof(cap)); var localCaps = this.Segment.Message.LocalCaps; uint? capId = null; for (uint i = 0; i < localCaps.Count; i++) { ref Message.CapEntry capEntry = ref localCaps[i]; if (capEntry.Capability == cap) { capEntry.RefCount++; capId = i; break; } } if (capId == null) { ref Message.CapEntry capEntry = ref localCaps.Add(out var id); capEntry.Capability = cap; capEntry.RefCount = 1; capId = id; } var p = new Pointer() { Type = PointerType.Other, OtherPointerType = OtherPointerType.Capability, CapabilityId = capId.Value }; _segment.GetWord(_structWordOffset + this.DataWords + pointerIndex) = p.RawValue; } private void WritePointerCore(int pointerIndex, Segment destSegment, int absOffset, Pointer tag) { if (pointerIndex < 0 || pointerIndex >= this.PointerWords) { throw new ArgumentOutOfRangeException("pointerIndex", "Pointer index out of range"); } var msg = _segment.Message; if (destSegment.Message != msg) { throw new ArgumentException("Can't point to struct in different message"); } Pointer resultPointer; if (this.Segment == destSegment) { int pointerWordOffset = this.StructWordOffset + this.DataWords + pointerIndex + 1; resultPointer = tag; resultPointer.WordOffset = absOffset - pointerWordOffset; } else { if (destSegment.TryAllocate(1, out int padOffset)) { tag.WordOffset = absOffset - (padOffset + 1); destSegment.GetWord(padOffset) = tag.RawValue; resultPointer = new FarPointer { Type = PointerType.Far, LandingPadOffset = (uint)padOffset, TargetSegmentId = (uint)destSegment.SegmentIndex, }; } else { _segment.Message.Allocate(2, out padOffset, out Segment segment); segment.GetWord(padOffset) = new FarPointer { Type = PointerType.Far, LandingPadOffset = (uint)absOffset, TargetSegmentId = (uint)destSegment.SegmentIndex }.RawValue; tag.WordOffset = 0; segment.GetWord(padOffset + 1) = tag.RawValue; resultPointer = new FarPointer { Type = PointerType.Far, IsDoubleFar = true, LandingPadOffset = (uint)padOffset, TargetSegmentId = (uint)segment.SegmentIndex, }; } } _segment.GetWord(_structWordOffset + this.DataWords + pointerIndex) = resultPointer.RawValue; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Write<T>(int index, T value) where T : struct { if (_upgradedListElementByteOffset >= 0) { if (index > 0) throw new InvalidOperationException("Cannot write to struct from a non-composite list"); Unsafe.As<byte, T>(ref _segment.GetByte(_structWordOffset * sizeof(ulong) + _upgradedListElementByteOffset)) = value; } Unsafe.As<byte, T>(ref _segment.GetByte(_structWordOffset * sizeof(ulong) + index * Unsafe.SizeOf<T>())) = value; } public void WriteInt8(int index, sbyte value, sbyte defaultValue = 0) => this.Write(index, value ^ defaultValue); public void WriteUInt8(int index, byte value, byte defaultValue = 0) => this.Write(index, value ^ defaultValue); public void WriteInt16(int index, short value, short defaultValue = 0) => this.Write(index, value ^ defaultValue); public void WriteUInt16(int index, ushort value, ushort defaultValue = 0) => this.Write(index, value ^ defaultValue); public void WriteInt32(int index, int value, int defaultValue = 0) => this.Write(index, value ^ defaultValue); public void WriteUInt32(int index, uint value, uint defaultValue = 0) => this.Write(index, value ^ defaultValue); public void WriteInt64(int index, long value, long defaultValue = 0) => this.Write(index, value ^ defaultValue); public void WriteUInt64(int index, ulong value, ulong defaultValue = 0) => this.Write(index, value ^ defaultValue); public void WriteFloat32(int index, float value, float defaultValue = 0) => this.Write(index, TypeHelpers.Xor(value, defaultValue)); public void WriteFloat64(int index, double value, double defaultValue = 0) => this.Write(index, TypeHelpers.Xor(value, defaultValue)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteBool(int index, bool value, bool defaultValue = false) { if (_upgradedListElementByteOffset >= 0 && index > 0) { throw new InvalidOperationException("Cannot write to struct from a non-composite list"); } var wordIndex = index >> 6; if (wordIndex >= this.DataWords) throw new IndexOutOfRangeException(); var mask = 1UL << (index & 63); if (value != defaultValue) { _segment.GetWord(_structWordOffset + wordIndex) |= mask; } else { _segment.GetWord(_structWordOffset + wordIndex) &= ~mask; } } #endregion Write methods } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. // Licensed under the MIT License. using System; using System.Windows; namespace InteractiveDataDisplay.WPF { /// <summary> /// Performs transformations between data values and plot coordinates. /// </summary> public abstract class DataTransform : DependencyObject { /// <summary>Gets range of valid data values. <see cref="DataToPlot"/> method returns NaN for /// values outside this range. /// </summary> public Range Domain { get; private set; } /// <summary> /// Initializes a new instance of <see cref="DataTransform"/> class. /// </summary> /// <param name="domain">A range of valid data.</param> protected DataTransform(Range domain) { Domain = domain; } /// <summary> /// Converts value from data to plot coordinates. /// </summary> /// <param name="dataValue">A value in data coordinates.</param> /// <returns>Value converted to plot coordinates or NaN if <paramref name="dataValue"/> /// falls outside of <see cref="Domain"/>.</returns> public abstract double DataToPlot(double dataValue); /// <summary> /// Converts value from plot coordinates to data. /// </summary> /// <param name="plotValue">A value in plot coordinates.</param> /// <returns>Value converted to data coordinates or NaN if no value in data coordinates /// matches <paramref name="plotValue"/>.</returns> public abstract double PlotToData(double plotValue); /// <summary>Identity transformation</summary> public static readonly DataTransform Identity = new IdentityDataTransform(); } /// <summary> /// Provides identity transformation between data and plot coordinates. /// </summary> public class IdentityDataTransform : DataTransform { /// <summary> /// Initializes a new instance of <see cref="IdentityDataTransform"/> class. /// </summary> public IdentityDataTransform() : base(new Range(double.MinValue, double.MaxValue)) { } /// <summary> /// Returns a value in data coordinates without convertion. /// </summary> /// <param name="dataValue">A value in data coordinates.</param> /// <returns></returns> public override double DataToPlot(double dataValue) { return dataValue; } /// <summary> /// Returns a value in plot coordinates without convertion. /// </summary> /// <param name="plotValue">A value in plot coordinates.</param> /// <returns></returns> public override double PlotToData(double plotValue) { return plotValue; } } /// <summary> /// Represents a mercator transform, used in maps. /// Transforms y coordinates. /// </summary> public sealed class MercatorTransform : DataTransform { /// <summary> /// Initializes a new instance of the <see cref="MercatorTransform"/> class. /// </summary> public MercatorTransform() : base(new Range(-85, 85)) { CalcScale(maxLatitude); } /// <summary> /// Initializes a new instance of the <see cref="MercatorTransform"/> class. /// </summary> /// <param name="maxLatitude">The maximal latitude.</param> public MercatorTransform(double maxLatitude) : base(new Range(-maxLatitude, maxLatitude)) { this.maxLatitude = maxLatitude; CalcScale(maxLatitude); } private void CalcScale(double inputMaxLatitude) { double maxLatDeg = inputMaxLatitude; double maxLatRad = maxLatDeg * Math.PI / 180; scale = maxLatDeg / Math.Log(Math.Tan(maxLatRad / 2 + Math.PI / 4)); } private double scale; /// <summary> /// Gets the scale. /// </summary> /// <value>The scale.</value> public double Scale { get { return scale; } } private double maxLatitude = 85; /// <summary> /// Gets the maximal latitude. /// </summary> /// <value>The max latitude.</value> public double MaxLatitude { get { return maxLatitude; } } /// <summary> /// Converts value from mercator to plot coordinates. /// </summary> /// <param name="dataValue">A value in mercator coordinates.</param> /// <returns>Value converted to plot coordinates.</returns> public override double DataToPlot(double dataValue) { if (-maxLatitude <= dataValue && dataValue <= maxLatitude) { dataValue = scale * Math.Log(Math.Tan(Math.PI * (dataValue + 90) / 360)); } return dataValue; } /// <summary> /// Converts value from plot to mercator coordinates. /// </summary> /// <param name="plotValue">A value in plot coordinates.</param> /// <returns>Value converted to mercator coordinates.</returns> public override double PlotToData(double plotValue) { if (-maxLatitude <= plotValue && plotValue <= maxLatitude) { double e = Math.Exp(plotValue / scale); plotValue = 360 * Math.Atan(e) / Math.PI - 90; } return plotValue; } } /// <summary> /// Provides linear transform u = <see cref="Scale"/> * d + <see cref="Offset"/> from data value d to plot coordinate u. /// </summary> public sealed class LinearDataTransform : DataTransform { /// <summary> /// Gets or sets the scale factor. /// </summary> public double Scale { get { return (double)GetValue(ScaleProperty); } set { SetValue(ScaleProperty, value); } } /// <summary> /// Identifies the <see cref="Scale"/> dependency property. /// </summary> public static readonly DependencyProperty ScaleProperty = DependencyProperty.Register("Scale", typeof(double), typeof(LinearDataTransform), new PropertyMetadata(1.0)); /// <summary> /// Gets or sets the distance to translate an value. /// </summary> public double Offset { get { return (double)GetValue(OffsetProperty); } set { SetValue(OffsetProperty, value); } } /// <summary> /// Identifies the <see cref="Offset"/> dependency property. /// </summary> public static readonly DependencyProperty OffsetProperty = DependencyProperty.Register("Offset", typeof(double), typeof(LinearDataTransform), new PropertyMetadata(0.0)); /// <summary> /// Initializes a new instance of the <see cref="LinearDataTransform"/> class. /// </summary> public LinearDataTransform() : base(new Range(double.MinValue, double.MaxValue)) { } /// <summary> /// Transforms a value according to defined <see cref="Scale"/> and <see cref="Offset"/>. /// </summary> /// <param name="dataValue">A value in data coordinates.</param> /// <returns>Transformed value.</returns> public override double DataToPlot(double dataValue) { return dataValue * Scale + Offset; } /// <summary> /// Returns a value in data coordinates from its transformed value. /// </summary> /// <param name="plotValue">Transformed value.</param> /// <returns>Original value or NaN if <see cref="Scale"/> is 0.</returns> public override double PlotToData(double plotValue) { if (Scale != 0) { return (plotValue - Offset) / Scale; } else return double.NaN; } } }
using System; using System.Collections; using System.Security; using System.Security.Permissions; using System.Windows; using System.Windows.Media; using System.Windows.Threading; using MS.Internal; using MS.Internal.PresentationCore; // SecurityHelper using MS.Win32; // VK translation. using System.Windows.Automation.Peers; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; #pragma warning disable 1634, 1691 // suppressing PreSharp warnings namespace System.Windows.Input { /// <summary> /// The KeyboardDevice class represents the mouse device to the /// members of a context. /// </summary> public abstract class KeyboardDevice : InputDevice { /// <SecurityNote> /// Critical: This code creates critical data(_tsfManager,_textcompositionManager) and stores critical data (inputManager) /// TreatAsSafe: Although it creates critical data there are demand on the critical data and the constructor is safe /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] protected KeyboardDevice(InputManager inputManager) { _inputManager = new SecurityCriticalDataClass<InputManager>(inputManager); _inputManager.Value.PreProcessInput += new PreProcessInputEventHandler(PreProcessInput); _inputManager.Value.PreNotifyInput += new NotifyInputEventHandler(PreNotifyInput); _inputManager.Value.PostProcessInput += new ProcessInputEventHandler(PostProcessInput); _isEnabledChangedEventHandler = new DependencyPropertyChangedEventHandler(OnIsEnabledChanged); _isVisibleChangedEventHandler = new DependencyPropertyChangedEventHandler(OnIsVisibleChanged); _focusableChangedEventHandler = new DependencyPropertyChangedEventHandler(OnFocusableChanged); _reevaluateFocusCallback = new DispatcherOperationCallback(ReevaluateFocusCallback); _reevaluateFocusOperation = null; // _TsfManager = new SecurityCriticalDataClass<TextServicesManager>(new TextServicesManager(inputManager)); _textcompositionManager = new SecurityCriticalData<TextCompositionManager>(new TextCompositionManager(inputManager)); } /// <summary> /// Gets the current state of the specified key from the device from the underlying system /// </summary> /// <param name="key"> /// Key to get the state of /// </param> /// <returns> /// The state of the specified key /// </returns> protected abstract KeyStates GetKeyStatesFromSystem( Key key ); /// <summary> /// Returns the element that input from this device is sent to. /// </summary> public override IInputElement Target { get { //VerifyAccess(); if(null != ForceTarget) return ForceTarget; return FocusedElement; } } internal IInputElement ForceTarget { get { return (IInputElement) _forceTarget; } set { _forceTarget = value as DependencyObject; } } /// <summary> /// Returns the PresentationSource that is reporting input for this device. /// </summary> /// <remarks> /// Callers must have UIPermission(PermissionState.Unrestricted) to call this API. /// </remarks> ///<SecurityNote> /// Critical - accesses critical data ( _activeSource) /// PublicOK - there is a demand. ///</SecurityNote> public override PresentationSource ActiveSource { [SecurityCritical ] get { SecurityHelper.DemandUnrestrictedUIPermission(); //VerifyAccess(); if (_activeSource != null) { return _activeSource.Value; } return null; } } /// <summary> /// The default mode for restoring focus. /// <summary> public RestoreFocusMode DefaultRestoreFocusMode {get; set;} /// <summary> /// Returns the element that the keyboard is focused on. /// </summary> public IInputElement FocusedElement { get { // VerifyAccess(); return (IInputElement) _focus; } } /// <summary> /// Clears focus. /// </summary> public void ClearFocus() { Focus(null, false, false, false); } /// <summary> /// Focuses the keyboard on a particular element. /// </summary> /// <param name="element"> /// The element to focus the keyboard on. /// </param> /// <SecurityNote> /// Critical: This code accesses _activeSource.Value. /// PublicOK: Moving focus within an app is safe and this does not expose /// the critical data. /// </SecurityNote> [SecurityCritical] public IInputElement Focus(IInputElement element) { DependencyObject oFocus = null; bool forceToNullIfFailed = false; // Validate that if elt is either a UIElement or a ContentElement. if(element != null) { if(!InputElement.IsValid(element)) { #pragma warning suppress 6506 // element is obviously not null throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, element.GetType())); } oFocus = (DependencyObject) element; } // If no element is given for focus, use the root of the active source. if(oFocus == null && _activeSource != null) { oFocus = _activeSource.Value.RootVisual as DependencyObject; forceToNullIfFailed = true; } Focus(oFocus, true, true, forceToNullIfFailed); return (IInputElement) _focus; } /// <SecurityNote> /// Critical: This code calls into PresentationSource. which is not safe to expose. /// Additonally it retrieves the keyboard input provider /// TreatAsSafe: Moving focus within an app is safe and this does not expose /// the critical data. /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] private void Focus(DependencyObject focus, bool askOld, bool askNew, bool forceToNullIfFailed) { // Make sure that the element is valid for receiving focus. bool isValid = true; if(focus != null) { isValid = Keyboard.IsFocusable(focus); if(!isValid && forceToNullIfFailed) { focus = null; isValid = true; } } if(isValid) { // Get the keyboard input provider that provides input for the active source. IKeyboardInputProvider keyboardInputProvider = null; DependencyObject containingVisual = InputElement.GetContainingVisual(focus); if(containingVisual != null) { PresentationSource source = PresentationSource.CriticalFromVisual(containingVisual); if (source != null) { keyboardInputProvider = (IKeyboardInputProvider)source.GetInputProvider(typeof(KeyboardDevice)); } } // Start the focus-change operation. TryChangeFocus(focus, keyboardInputProvider, askOld, askNew, forceToNullIfFailed); } } /// <summary> /// Returns the set of modifier keys currently pressed as determined by querying our keyboard state cache /// </summary> public ModifierKeys Modifiers { get { // VerifyAccess(); ModifierKeys modifiers = ModifierKeys.None; if(IsKeyDown_private(Key.LeftAlt) || IsKeyDown_private(Key.RightAlt)) { modifiers |= ModifierKeys.Alt; } if(IsKeyDown_private(Key.LeftCtrl) || IsKeyDown_private(Key.RightCtrl)) { modifiers |= ModifierKeys.Control; } if(IsKeyDown_private(Key.LeftShift) || IsKeyDown_private(Key.RightShift)) { modifiers |= ModifierKeys.Shift; } return modifiers; } } /// <summary> /// There is a proscription against using Enum.IsDefined(). (it is slow) /// so we write these PRIVATE validate routines instead. /// </summary> private void Validate_Key(Key key) { if( 256 <= (int)key || (int)key <= 0) throw new System.ComponentModel.InvalidEnumArgumentException("key", (int)key, typeof(Key)); } /// <summary> /// This is the core private method that returns whether or not the specified key /// is down. It does it without the extra argument validation and context checks. /// </summary> private bool IsKeyDown_private(Key key) { return ( ( GetKeyStatesFromSystem(key) & KeyStates.Down ) == KeyStates.Down ); } /// <summary> /// Returns whether or not the specified key is down. /// </summary> public bool IsKeyDown(Key key) { // VerifyAccess(); Validate_Key(key); return IsKeyDown_private(key); } /// <summary> /// Returns whether or not the specified key is up. /// </summary> public bool IsKeyUp(Key key) { // VerifyAccess(); Validate_Key(key); return (!IsKeyDown_private(key)); } /// <summary> /// Returns whether or not the specified key is toggled. /// </summary> public bool IsKeyToggled(Key key) { // VerifyAccess(); Validate_Key(key); return( ( GetKeyStatesFromSystem(key) & KeyStates.Toggled ) == KeyStates.Toggled ); } /// <summary> /// Returns the state of the specified key. /// </summary> public KeyStates GetKeyStates(Key key) { // VerifyAccess(); Validate_Key(key); return GetKeyStatesFromSystem(key); } /// <SecurityNote> /// Critical:This entity is not safe to give out /// </SecurityNote> internal TextServicesManager TextServicesManager { [SecurityCritical,SecurityTreatAsSafe] get { SecurityHelper.DemandUnrestrictedUIPermission(); return _TsfManager.Value; } } /// <SecurityNote> /// Critical:This entity is not safe to give out /// </SecurityNote> internal TextCompositionManager TextCompositionManager { [SecurityCritical,SecurityTreatAsSafe] get { SecurityHelper.DemandUnrestrictedUIPermission(); return _textcompositionManager.Value; } } /// <SecurityNote> /// Critical: This code accesses critical data (inputManager) and /// causes a change of focus. /// TreatAsSafe:This code is safe to expose /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] private void TryChangeFocus(DependencyObject newFocus, IKeyboardInputProvider keyboardInputProvider, bool askOld, bool askNew, bool forceToNullIfFailed) { bool changeFocus = true; int timeStamp = Environment.TickCount ; DependencyObject oldFocus = _focus; // This is required, used below to see if focus has been delegated if(newFocus != _focus) { // If requested, and there is currently something with focus // Send the PreviewLostKeyboardFocus event to see if the object losing focus want to cancel it. // - no need to check "changeFocus" here as it was just previously unconditionally set to true if(askOld && _focus != null) { KeyboardFocusChangedEventArgs previewLostFocus = new KeyboardFocusChangedEventArgs(this, timeStamp, (IInputElement)_focus, (IInputElement)newFocus); previewLostFocus.RoutedEvent=Keyboard.PreviewLostKeyboardFocusEvent; previewLostFocus.Source= _focus; if(_inputManager != null) _inputManager.Value.ProcessInput(previewLostFocus); // if(previewLostFocus.Handled) { changeFocus = false; } } // If requested, and there is an object to specified to take focus // Send the PreviewGotKeyboardFocus event to see if the object gaining focus want to cancel it. // - must also check "changeFocus", no point in checking if the "previewLostFocus" event // above already cancelled it if(askNew && changeFocus && newFocus != null) { KeyboardFocusChangedEventArgs previewGotFocus = new KeyboardFocusChangedEventArgs(this, timeStamp, (IInputElement)_focus, (IInputElement)newFocus); previewGotFocus.RoutedEvent=Keyboard.PreviewGotKeyboardFocusEvent; previewGotFocus.Source= newFocus; if(_inputManager != null) _inputManager.Value.ProcessInput(previewGotFocus); // if(previewGotFocus.Handled) { changeFocus = false; } } // If we are setting the focus to an element, see if the InputProvider // can take focus for us. if(changeFocus && newFocus != null) { if (keyboardInputProvider != null && Keyboard.IsFocusable(newFocus)) { // Tell the element we are about to acquire focus through // the input provider. The element losing focus and the // element receiving focus have all agreed to the // transaction. This is used by menus to configure the // behavior of focus changes. KeyboardInputProviderAcquireFocusEventArgs acquireFocus = new KeyboardInputProviderAcquireFocusEventArgs(this, timeStamp, changeFocus); acquireFocus.RoutedEvent = Keyboard.PreviewKeyboardInputProviderAcquireFocusEvent; acquireFocus.Source= newFocus; if(_inputManager != null) _inputManager.Value.ProcessInput(acquireFocus); // Acquire focus through the input provider. changeFocus = keyboardInputProvider.AcquireFocus(false); // Tell the element whether or not we were able to // acquire focus through the input provider. acquireFocus = new KeyboardInputProviderAcquireFocusEventArgs(this, timeStamp, changeFocus); acquireFocus.RoutedEvent = Keyboard.KeyboardInputProviderAcquireFocusEvent; acquireFocus.Source= newFocus; if(_inputManager != null) _inputManager.Value.ProcessInput(acquireFocus); } else { changeFocus = false; } } // If the ChangeFocus operation was cancelled or the AcquireFocus operation failed // and the "ForceToNullIfFailed" flag was set, we set focus to null if( !changeFocus && forceToNullIfFailed && oldFocus == _focus /* Focus is not delegated */ ) { // focus might be delegated (e.g. during PreviewGotKeyboardFocus) // without actually changing, if it was already on the delegated // element (see bug 1794057). We can't test for this directly, // but if focus is within the desired element we'll assume this // is what happened. IInputElement newFocusElement = newFocus as IInputElement; if (newFocusElement == null || !newFocusElement.IsKeyboardFocusWithin) { newFocus = null; changeFocus = true; } } // If both the old and new focus elements allowed it, and the // InputProvider has acquired it, go ahead and change our internal // sense of focus to the desired element. if(changeFocus) { ChangeFocus(newFocus, timeStamp); } } } /// <SecurityNote> /// Critical: This code accesses critical data (inputManager,_TsfManager,_inputManager) and /// is not OK to expose /// TreatAsSafe: This changes focus within an app /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] private void ChangeFocus(DependencyObject focus, int timestamp) { DependencyObject o = null; if(focus != _focus) { // Update the critical pieces of data. DependencyObject oldFocus = _focus; _focus = focus; _focusRootVisual = InputElement.GetRootVisual(focus); using(Dispatcher.DisableProcessing()) // Disable reentrancy due to locks taken { // Adjust the handlers we use to track everything. if(oldFocus != null) { o = oldFocus; if (InputElement.IsUIElement(o)) { ((UIElement)o).IsEnabledChanged -= _isEnabledChangedEventHandler; ((UIElement)o).IsVisibleChanged -= _isVisibleChangedEventHandler; ((UIElement)o).FocusableChanged -= _focusableChangedEventHandler; } else if (InputElement.IsContentElement(o)) { ((ContentElement)o).IsEnabledChanged -= _isEnabledChangedEventHandler; // NOTE: there is no IsVisible property for ContentElements. ((ContentElement)o).FocusableChanged -= _focusableChangedEventHandler; } else { ((UIElement3D)o).IsEnabledChanged -= _isEnabledChangedEventHandler; ((UIElement3D)o).IsVisibleChanged -= _isVisibleChangedEventHandler; ((UIElement3D)o).FocusableChanged -= _focusableChangedEventHandler; } } if(_focus != null) { o = _focus; if (InputElement.IsUIElement(o)) { ((UIElement)o).IsEnabledChanged += _isEnabledChangedEventHandler; ((UIElement)o).IsVisibleChanged += _isVisibleChangedEventHandler; ((UIElement)o).FocusableChanged += _focusableChangedEventHandler; } else if (InputElement.IsContentElement(o)) { ((ContentElement)o).IsEnabledChanged += _isEnabledChangedEventHandler; // NOTE: there is no IsVisible property for ContentElements. ((ContentElement)o).FocusableChanged += _focusableChangedEventHandler; } else { ((UIElement3D)o).IsEnabledChanged += _isEnabledChangedEventHandler; ((UIElement3D)o).IsVisibleChanged += _isVisibleChangedEventHandler; ((UIElement3D)o).FocusableChanged += _focusableChangedEventHandler; } } } // Oddly enough, update the FocusWithinProperty properties first. This is // so any callbacks will see the more-common FocusWithinProperty properties // set correctly. UIElement.FocusWithinProperty.OnOriginValueChanged(oldFocus, _focus, ref _focusTreeState); // Invalidate the IsKeyboardFocused properties. if(oldFocus != null) { o = oldFocus; o.SetValue(UIElement.IsKeyboardFocusedPropertyKey, false); // Same property for ContentElements } if(_focus != null) { // Invalidate the IsKeyboardFocused property. o = _focus; o.SetValue(UIElement.IsKeyboardFocusedPropertyKey, true); // Same property for ContentElements } // Call TestServicesManager change the focus of the InputMethod is enable/disabled accordingly // so it's ready befere the GotKeyboardFocusEvent handler is invoked. if (_TsfManager != null) _TsfManager.Value.Focus(_focus); // InputLanguageManager checks the preferred input languages. // This should before GotEvent because the preferred input language // should be set at the event handler. InputLanguageManager.Current.Focus(_focus, oldFocus); // Send the LostKeyboardFocus and GotKeyboardFocus events. if(oldFocus != null) { KeyboardFocusChangedEventArgs lostFocus = new KeyboardFocusChangedEventArgs(this, timestamp, (IInputElement) oldFocus, (IInputElement) focus); lostFocus.RoutedEvent=Keyboard.LostKeyboardFocusEvent; lostFocus.Source= oldFocus; if(_inputManager != null) _inputManager.Value.ProcessInput(lostFocus); } if(_focus != null) { KeyboardFocusChangedEventArgs gotFocus = new KeyboardFocusChangedEventArgs(this, timestamp, (IInputElement) oldFocus, (IInputElement) _focus); gotFocus.RoutedEvent=Keyboard.GotKeyboardFocusEvent; gotFocus.Source= _focus; if(_inputManager!=null) _inputManager.Value.ProcessInput(gotFocus); } // InputMethod checks the preferred ime state. // The preferred input methods should be applied after Cicero TIP gots SetFocus callback. InputMethod.Current.GotKeyboardFocus(_focus); //Could be also built-in into IsKeyboardFocused_Changed static on UIElement and ContentElement //However the Automation likes to go immediately back on us so it would be better be last one... AutomationPeer.RaiseFocusChangedEventHelper((IInputElement)_focus); } } private void OnIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e) { // The element with focus just became disabled. // // We can't leave focus on a disabled element, so move it. ReevaluateFocusAsync(null, null, false); } private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { // The element with focus just became non-visible (collapsed or hidden). // // We can't leave focus on a non-visible element, so move it. ReevaluateFocusAsync(null, null, false); } private void OnFocusableChanged(object sender, DependencyPropertyChangedEventArgs e) { // The element with focus just became unfocusable. // // We can't leave focus on an unfocusable element, so move it. ReevaluateFocusAsync(null, null, false); } /// <summary> /// Determines if we can remain focused on the element we think has focus /// </summary> /// <remarks> /// Queues an invocation of ReevaluateFocusCallback to do the actual work. /// - that way if the object that had focus has only been temporarily /// removed, disable, etc. and will eventually be valid again, we /// avoid needlessly killing focus. /// </remarks> internal void ReevaluateFocusAsync(DependencyObject element, DependencyObject oldParent, bool isCoreParent) { if(element != null) { if(isCoreParent) { FocusTreeState.SetCoreParent(element, oldParent); } else { FocusTreeState.SetLogicalParent(element, oldParent); } } // It would be best to re-evaluate anything dependent on the hit-test results // immediately after layout & rendering are complete. Unfortunately this can // lead to an infinite loop. Consider the following scenario: // // If the mouse is over an element, hide it. // // This never resolves to a "correct" state. When the mouse moves over the // element, the element is hidden, so the mouse is no longer over it, so the // element is shown, but that means the mouse is over it again. Repeat. // // We push our re-evaluation to a priority lower than input processing so that // the user can change the input device to avoid the infinite loops, or close // the app if nothing else works. // if(_reevaluateFocusOperation == null) { _reevaluateFocusOperation = Dispatcher.BeginInvoke(DispatcherPriority.Input, _reevaluateFocusCallback, null); } } /// <summary> /// Determines if we can remain focused on the element we think has focus /// </summary> /// <remarks> /// Invoked asynchronously by ReevaluateFocusAsync. /// Confirms that the element we think has focus is: /// - still enabled /// - still visible /// - still in the tree /// </remarks> ///<SecurityNote> /// Critical: accesses critical data ( _activeSource) /// TreatAsSafe: Moving focus within an app is safe and this does not expose /// the critical data. ///</SecurityNote> [SecurityCritical,SecurityTreatAsSafe] private object ReevaluateFocusCallback(object arg) { _reevaluateFocusOperation = null; if( _focus == null ) { return null; } // // Reevaluate the eligability of the focused element to actually // have focus. If that element is no longer focusable, then search // for an ancestor that is. // DependencyObject element = _focus; while(element != null) { if(Keyboard.IsFocusable(element)) { break; } // Walk the current tree structure. element = DeferredElementTreeState.GetCoreParent(element, null); } // Get the PresentationSource that contains the element to be focused. PresentationSource presentationSource = null; DependencyObject visualContainer = InputElement.GetContainingVisual(element); if(visualContainer != null) { presentationSource = PresentationSource.CriticalFromVisual(visualContainer); } // The default action is to reset focus to the root element // of the active presentation source. bool moveFocus = true; DependencyObject moveFocusTo = null; if(presentationSource != null) { IKeyboardInputProvider keyboardProvider = presentationSource.GetInputProvider(typeof(KeyboardDevice)) as IKeyboardInputProvider; if(keyboardProvider != null) { // Confirm with the keyboard provider for this // presentation source that it has acquired focus. if(keyboardProvider.AcquireFocus(true)) { if(element == _focus) { // The focus element is still good. moveFocus = false; } else { // The focus element is no longer focusable, but we found // an ancestor that is, so move focus there. moveFocus = true; moveFocusTo = element; } } } } if(moveFocus) { if(moveFocusTo == null && _activeSource != null) { moveFocusTo = _activeSource.Value.RootVisual as DependencyObject; } Focus(moveFocusTo, /*askOld=*/ false, /*askNew=*/ true, /*forceToNullIfFailed=*/ true); } else { // Refresh FocusWithinProperty so that ReverseInherited Flags are updated. // // We only need to do this if there is any information about the old // tree structure. if(_focusTreeState != null && !_focusTreeState.IsEmpty) { UIElement.FocusWithinProperty.OnOriginValueChanged(_focus, _focus, ref _focusTreeState); } } return null; } /// <SecurityNote> /// Critical: accesses e.StagingItem.Input /// </SecurityNote> [SecurityCritical] private void PreProcessInput(object sender, PreProcessInputEventArgs e) { RawKeyboardInputReport keyboardInput = ExtractRawKeyboardInputReport(e, InputManager.PreviewInputReportEvent); if(keyboardInput != null) { // Claim the input for the keyboard. e.StagingItem.Input.Device = this; } } /// <SecurityNote> /// Critical: This code can be used for input spoofing, /// It also stores critical data InputSource /// accesses e.StagingItem.Input /// </SecurityNote> [SecurityCritical] private void PreNotifyInput(object sender, NotifyInputEventArgs e) { RawKeyboardInputReport keyboardInput = ExtractRawKeyboardInputReport(e, InputManager.PreviewInputReportEvent); if(keyboardInput != null) { CheckForDisconnectedFocus(); // Activation // // MITIGATION: KEYBOARD_STATE_OUT_OF_[....] // // It is very important that we allow multiple activate events. // This is how we deal with the fact that Win32 sometimes sends // us a WM_SETFOCUS message BEFORE it has updated it's internal // internal keyboard state information. When we get the // WM_SETFOCUS message, we activate the keyboard with the // keyboard state (even though it could be wrong). Then when // we get the first "real" keyboard input event, we activate // the keyboard again, since Win32 will have updated the // keyboard state correctly by then. // if((keyboardInput.Actions & RawKeyboardActions.Activate) == RawKeyboardActions.Activate) { //if active source is null, no need to do special-case handling if(_activeSource == null) { // we are now active. _activeSource = new SecurityCriticalDataClass<PresentationSource>(keyboardInput.InputSource); } else if(_activeSource.Value != keyboardInput.InputSource) { IKeyboardInputProvider toDeactivate = _activeSource.Value.GetInputProvider(typeof(KeyboardDevice)) as IKeyboardInputProvider; // we are now active. _activeSource = new SecurityCriticalDataClass<PresentationSource>(keyboardInput.InputSource); if(toDeactivate != null) { toDeactivate.NotifyDeactivate(); } } } // Generally, we need to check against redundant actions. // We never prevet the raw event from going through, but we // will only generate the high-level events for non-redundant // actions. We store the set of non-redundant actions in // the dictionary of this event. // If the input is reporting a key down, the action is never // considered redundant. if((keyboardInput.Actions & RawKeyboardActions.KeyDown) == RawKeyboardActions.KeyDown) { RawKeyboardActions actions = GetNonRedundantActions(e); actions |= RawKeyboardActions.KeyDown; e.StagingItem.SetData(_tagNonRedundantActions, actions); // Pass along the key that was pressed, and update our state. Key key = KeyInterop.KeyFromVirtualKey(keyboardInput.VirtualKey); e.StagingItem.SetData(_tagKey, key); e.StagingItem.SetData(_tagScanCode, new ScanCode(keyboardInput.ScanCode, keyboardInput.IsExtendedKey)); // Tell the InputManager that the MostRecentDevice is us. if(_inputManager!=null) _inputManager.Value.MostRecentInputDevice = this; } // if((keyboardInput.Actions & RawKeyboardActions.KeyUp) == RawKeyboardActions.KeyUp) { RawKeyboardActions actions = GetNonRedundantActions(e); actions |= RawKeyboardActions.KeyUp; e.StagingItem.SetData(_tagNonRedundantActions, actions); // Pass along the key that was pressed, and update our state. Key key = KeyInterop.KeyFromVirtualKey(keyboardInput.VirtualKey); e.StagingItem.SetData(_tagKey, key); e.StagingItem.SetData(_tagScanCode, new ScanCode(keyboardInput.ScanCode, keyboardInput.IsExtendedKey)); // Tell the InputManager that the MostRecentDevice is us. if(_inputManager!=null) _inputManager.Value.MostRecentInputDevice = this; } } // On KeyDown, we might need to set the Repeat flag if(e.StagingItem.Input.RoutedEvent == Keyboard.PreviewKeyDownEvent) { CheckForDisconnectedFocus(); KeyEventArgs args = (KeyEventArgs) e.StagingItem.Input; // Is this the same as the previous key? (Look at the real key, e.g. TextManager // might have changed args.Key it to Key.TextInput.) if (_previousKey == args.RealKey) { // Yes, this is a repeat (we got the keydown for it twice, with no KeyUp in between) args.SetRepeat(true); } // Otherwise, keep this key to check against next time. else { _previousKey = args.RealKey; args.SetRepeat(false); } } // On KeyUp, we clear Repeat flag else if(e.StagingItem.Input.RoutedEvent == Keyboard.PreviewKeyUpEvent) { CheckForDisconnectedFocus(); KeyEventArgs args = (KeyEventArgs) e.StagingItem.Input; args.SetRepeat(false); // Clear _previousKey, so that down/up/down/up doesn't look like a repeat _previousKey = Key.None; } } /// <SecurityNote> /// Critical - calls critical functions PushInput, KeyEventArgs.UnsafeInputSource /// and KeyEventArgs ctor. /// accesses e.StagingItem.Input /// </SecurityNote> [SecurityCritical] private void PostProcessInput(object sender, ProcessInputEventArgs e) { // PreviewKeyDown --> KeyDown if(e.StagingItem.Input.RoutedEvent == Keyboard.PreviewKeyDownEvent) { CheckForDisconnectedFocus(); if(!e.StagingItem.Input.Handled) { KeyEventArgs previewKeyDown = (KeyEventArgs) e.StagingItem.Input; // Dig out the real key. bool isSystemKey = false; bool isImeProcessed = false; bool isDeadCharProcessed = false; Key key = previewKeyDown.Key; if (key == Key.System) { isSystemKey = true; key = previewKeyDown.RealKey; } else if (key == Key.ImeProcessed) { isImeProcessed = true; key = previewKeyDown.RealKey; } else if (key == Key.DeadCharProcessed) { isDeadCharProcessed = true; key = previewKeyDown.RealKey; } KeyEventArgs keyDown = new KeyEventArgs(this, previewKeyDown.UnsafeInputSource, previewKeyDown.Timestamp, key); keyDown.SetRepeat( previewKeyDown.IsRepeat ); // Mark the new event as SystemKey as appropriate. if (isSystemKey) { keyDown.MarkSystem(); } else if (isImeProcessed) { // Mark the new event as ImeProcessed as appropriate. keyDown.MarkImeProcessed(); } else if (isDeadCharProcessed) { keyDown.MarkDeadCharProcessed(); } keyDown.RoutedEvent=Keyboard.KeyDownEvent; keyDown.ScanCode = previewKeyDown.ScanCode; keyDown.IsExtendedKey = previewKeyDown.IsExtendedKey; e.PushInput(keyDown, e.StagingItem); } } // PreviewKeyUp --> KeyUp if(e.StagingItem.Input.RoutedEvent == Keyboard.PreviewKeyUpEvent) { CheckForDisconnectedFocus(); if(!e.StagingItem.Input.Handled) { KeyEventArgs previewKeyUp = (KeyEventArgs) e.StagingItem.Input; // Dig out the real key. bool isSystemKey = false; bool isImeProcessed = false; bool isDeadCharProcessed = false; Key key = previewKeyUp.Key; if (key == Key.System) { isSystemKey = true; key = previewKeyUp.RealKey; } else if (key == Key.ImeProcessed) { isImeProcessed = true; key = previewKeyUp.RealKey; } else if(key == Key.DeadCharProcessed) { isDeadCharProcessed = true; key = previewKeyUp.RealKey; } KeyEventArgs keyUp = new KeyEventArgs(this, previewKeyUp.UnsafeInputSource, previewKeyUp.Timestamp, key); // Mark the new event as SystemKey as appropriate. if (isSystemKey) { keyUp.MarkSystem(); } else if (isImeProcessed) { // Mark the new event as ImeProcessed as appropriate. keyUp.MarkImeProcessed(); } else if (isDeadCharProcessed) { keyUp.MarkDeadCharProcessed(); } keyUp.RoutedEvent=Keyboard.KeyUpEvent; keyUp.ScanCode = previewKeyUp.ScanCode; keyUp.IsExtendedKey = previewKeyUp.IsExtendedKey; e.PushInput(keyUp, e.StagingItem); } } RawKeyboardInputReport keyboardInput = ExtractRawKeyboardInputReport(e, InputManager.InputReportEvent); if(keyboardInput != null) { CheckForDisconnectedFocus(); if(!e.StagingItem.Input.Handled) { // In general, this is where we promote the non-redundant // reported actions to our premier events. RawKeyboardActions actions = GetNonRedundantActions(e); // Raw --> PreviewKeyDown if((actions & RawKeyboardActions.KeyDown) == RawKeyboardActions.KeyDown) { Key key = (Key) e.StagingItem.GetData(_tagKey); if(key != Key.None) { KeyEventArgs previewKeyDown = new KeyEventArgs(this, keyboardInput.InputSource, keyboardInput.Timestamp, key); ScanCode scanCode = (ScanCode)e.StagingItem.GetData(_tagScanCode); previewKeyDown.ScanCode = scanCode.Code; previewKeyDown.IsExtendedKey = scanCode.IsExtended; if (keyboardInput.IsSystemKey) { previewKeyDown.MarkSystem(); } previewKeyDown.RoutedEvent=Keyboard.PreviewKeyDownEvent; e.PushInput(previewKeyDown, e.StagingItem); } } // Raw --> PreviewKeyUp if((actions & RawKeyboardActions.KeyUp) == RawKeyboardActions.KeyUp) { Key key = (Key) e.StagingItem.GetData(_tagKey); if(key != Key.None) { KeyEventArgs previewKeyUp = new KeyEventArgs(this, keyboardInput.InputSource, keyboardInput.Timestamp, key); ScanCode scanCode = (ScanCode)e.StagingItem.GetData(_tagScanCode); previewKeyUp.ScanCode = scanCode.Code; previewKeyUp.IsExtendedKey = scanCode.IsExtended; if (keyboardInput.IsSystemKey) { previewKeyUp.MarkSystem(); } previewKeyUp.RoutedEvent=Keyboard.PreviewKeyUpEvent; e.PushInput(previewKeyUp, e.StagingItem); } } } // Deactivate if((keyboardInput.Actions & RawKeyboardActions.Deactivate) == RawKeyboardActions.Deactivate) { if(IsActive) { _activeSource = null; // Even if handled, a keyboard deactivate results in a lost focus. ChangeFocus(null, e.StagingItem.Input.Timestamp); } } } } /// <SecurityNote> /// Critical: accesses the StagingInput /// </SecurityNote> [SecurityCritical] private RawKeyboardInputReport ExtractRawKeyboardInputReport(NotifyInputEventArgs e, RoutedEvent Event) { RawKeyboardInputReport keyboardInput = null; InputReportEventArgs input = e.StagingItem.Input as InputReportEventArgs; if(input != null) { if(input.Report.Type == InputType.Keyboard && input.RoutedEvent == Event) { keyboardInput = input.Report as RawKeyboardInputReport; } } return keyboardInput; } private RawKeyboardActions GetNonRedundantActions(NotifyInputEventArgs e) { RawKeyboardActions actions; // The CLR throws a null-ref exception if it tries to unbox a // null. So we have to special case that. object o = e.StagingItem.GetData(_tagNonRedundantActions); if(o != null) { actions = (RawKeyboardActions) o; } else { actions = new RawKeyboardActions(); } return actions; } // private bool CheckForDisconnectedFocus() { bool wasDisconnected = false; if(InputElement.GetRootVisual (_focus as DependencyObject) != _focusRootVisual) { wasDisconnected = true; Focus (null); } return wasDisconnected; } /// <SecurityNote> /// Critical: accesses critical data (_inputSource) /// TreatAsSafe: doesn't expose critical data, just returns true/false. /// </SecurityNote> internal bool IsActive { [SecurityCritical, SecurityTreatAsSafe] get { return _activeSource != null && _activeSource.Value != null; } } private DeferredElementTreeState FocusTreeState { get { if (_focusTreeState == null) { _focusTreeState = new DeferredElementTreeState(); } return _focusTreeState; } } private SecurityCriticalDataClass<InputManager> _inputManager; private SecurityCriticalDataClass<PresentationSource> _activeSource; private DependencyObject _focus; private DeferredElementTreeState _focusTreeState; private DependencyObject _forceTarget; private DependencyObject _focusRootVisual; private Key _previousKey; private DependencyPropertyChangedEventHandler _isEnabledChangedEventHandler; private DependencyPropertyChangedEventHandler _isVisibleChangedEventHandler; private DependencyPropertyChangedEventHandler _focusableChangedEventHandler; private DispatcherOperationCallback _reevaluateFocusCallback; private DispatcherOperation _reevaluateFocusOperation; // Data tags for information we pass around the staging area. private object _tagNonRedundantActions = new object(); private object _tagKey = new object(); private object _tagScanCode = new object(); private class ScanCode { internal ScanCode(int code, bool isExtended) { _code = code; _isExtended = isExtended; } internal int Code {get {return _code;}} internal bool IsExtended {get {return _isExtended;}} private readonly int _code; private readonly bool _isExtended; } // private SecurityCriticalData<TextCompositionManager> _textcompositionManager; // TextServicesManager handles KeyDown -> IME composition conversion. /// <SecurityNote> /// This data is risky to give out since it is got under an elevation /// and can be used for risky operations /// </SecurityNote> private SecurityCriticalDataClass<TextServicesManager> _TsfManager; } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace RedditSharp { /// <summary>; /// The method by which the WebAgent will limit request rate /// </summary> public enum RateLimitMode { /// <summary> /// Limits requests to one every two seconds (one if OAuth) /// </summary> Pace, /// <summary> /// Restricts requests to five per ten seconds (ten if OAuth) /// </summary> SmallBurst, /// <summary> /// Restricts requests to thirty per minute (sixty if OAuth) /// </summary> Burst, /// <summary> /// Does not restrict request rate. ***NOT RECOMMENDED*** /// </summary> None } /// <summary> /// Class to manage API rate limiting /// </summary> public class RateLimitManager : IRateLimiter { // See https://github.com/reddit/reddit/wiki/API for more details. /// <summary> /// Current number of estimated used requests /// </summary> public int Used { get; private set; } /// <summary> /// Current estimate of remaining requests /// </summary> public int Remaining { get; private set; } /// <summary> /// Approximate seconds until the rate limit is reset. /// </summary> public DateTimeOffset Reset { get; private set; } /// <summary> /// It is strongly advised that you leave this set to Burst or Pace. Reddit bans excessive /// requests with extreme predjudice. /// </summary> public RateLimitMode Mode { get; set; } /// <summary> /// UTC DateTime of last request made to Reddit API /// </summary> public DateTime LastRequest { get; private set; } /// <summary> /// UTC DateTime of when the last burst started /// </summary> public DateTime BurstStart { get; private set; } /// <summary> /// Number of requests made during the current burst /// </summary> public int RequestsThisBurst { get; private set; } protected SemaphoreSlim rateLimitLock; public int RequestsPerMinuteWithOAuth { get; set; } public int RequestsPerMinuteWithoutOAuth { get; set; } /// <summary> /// Create new RateLimitManager. Defaults to Burst RateLimitMode /// </summary> /// <param name="mode">Defaults to Burst RateLimitMode</param> public RateLimitManager(RateLimitMode mode = RateLimitMode.Burst, int requestsPerMinuteWithOAuth = 60, int requestsPerMinuteWithoutOAuth = 30) { rateLimitLock = new SemaphoreSlim(1, 1); Reset = DateTimeOffset.UtcNow; Mode = mode; this.RequestsPerMinuteWithOAuth = requestsPerMinuteWithOAuth; this.RequestsPerMinuteWithoutOAuth = requestsPerMinuteWithoutOAuth; } /// <summary> /// Locks and awaits until you can make another request per RateLimitMode /// </summary> /// <param name="oauth"></param> /// <returns></returns> public async Task CheckRateLimitAsync(bool oauth) { await rateLimitLock.WaitAsync().ConfigureAwait(false); try { if (Remaining <= 0 && DateTime.UtcNow < Reset) { await Task.Delay(Reset - DateTime.UtcNow).ConfigureAwait(false); } else { await EnforceRateLimit(oauth); } } finally { rateLimitLock.Release(); } } /// <summary> /// Enforce the api throttle. /// </summary> public async Task EnforceRateLimit(bool oauth) { var limitRequestsPerMinute = oauth ? (double)this.RequestsPerMinuteWithOAuth : (double)this.RequestsPerMinuteWithoutOAuth; var requestTime = DateTime.UtcNow; switch (Mode) { case RateLimitMode.Pace: TimeSpan delayAmount = TimeSpan.FromSeconds(60 / limitRequestsPerMinute) - (DateTime.UtcNow - LastRequest); delayAmount = delayAmount.TotalMilliseconds < 0 ? new TimeSpan(0) : delayAmount; await Task.Delay(delayAmount).ConfigureAwait(false); break; case RateLimitMode.SmallBurst: //this is first request OR the burst expired if (RequestsThisBurst <= 0 || (DateTime.UtcNow - BurstStart).TotalSeconds >= 10) { BurstStart = DateTime.UtcNow; RequestsThisBurst = 0; } //limit has been reached if (RequestsThisBurst >= limitRequestsPerMinute / 6.0) { await Task.Delay((DateTime.UtcNow - BurstStart - TimeSpan.FromSeconds(10)).Duration()).ConfigureAwait(false); BurstStart = DateTime.UtcNow; RequestsThisBurst = 0; } RequestsThisBurst++; break; case RateLimitMode.Burst: //this is first request OR the burst expired if (RequestsThisBurst <= 0 || (DateTime.UtcNow - BurstStart).TotalSeconds >= 60) { BurstStart = DateTime.UtcNow; RequestsThisBurst = 0; } if (RequestsThisBurst >= limitRequestsPerMinute) //limit has been reached { await Task.Delay((DateTime.UtcNow - BurstStart - TimeSpan.FromSeconds(60)).Duration()).ConfigureAwait(false); BurstStart = DateTime.UtcNow; RequestsThisBurst = 0; } RequestsThisBurst++; break; } LastRequest = requestTime; } public async Task ReadHeadersAsync(HttpResponseMessage response) { await rateLimitLock.WaitAsync().ConfigureAwait(false); try { IEnumerable<string> values; var headers = response.Headers; int used, remaining; if (headers.TryGetValues("X-Ratelimit-Used", out values)) { used = int.Parse(values.First()); } else { return; } if (headers.TryGetValues("X-Ratelimit-Remaining", out values)) { remaining = (int)double.Parse(values.First(), CultureInfo.InvariantCulture); } else { return; } // Do not update values if they the limit has not been reset and // the show an impossible reduction in usage if (DateTime.UtcNow < Reset && (used < Used || remaining > Remaining)) return; Used = used; Remaining = remaining; if (headers.TryGetValues("X-Ratelimit-Reset", out values)) Reset = DateTime.UtcNow + TimeSpan.FromSeconds(int.Parse(values.First())); } finally { rateLimitLock.Release(); } } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Moq.Language; using Moq.Properties; namespace Moq.Linq { internal class MockSetupsBuilder : ExpressionVisitor { private static readonly string[] queryableMethods = new[] { "First", "Where", "FirstOrDefault" }; private static readonly string[] unsupportedMethods = new[] { "All", "Any", "Last", "LastOrDefault", "Single", "SingleOrDefault" }; private int stackIndex; private MethodCallExpression underlyingCreateMocks; public MockSetupsBuilder(MethodCallExpression underlyingCreateMocks) { this.underlyingCreateMocks = underlyingCreateMocks; } protected override Expression VisitBinary(BinaryExpression node) { if (node != null && this.stackIndex > 0) { if (node.NodeType != ExpressionType.Equal && node.NodeType != ExpressionType.AndAlso) throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Resources.LinqBinaryOperatorNotSupported, node.ToStringFixed())); if (node.NodeType == ExpressionType.Equal) { // TODO: throw if a matcher is used on either side of the expression. //ThrowIfMatcherIsUsed( // Account for the inverted assignment/querying like "false == foo.IsValid" scenario if (node.Left.NodeType == ExpressionType.Constant) // Invert left & right nodes in this case. return ConvertToSetup(node.Right, node.Left) ?? base.VisitBinary(node); else // Perform straight conversion where the right-hand side will be the setup return value. return ConvertToSetup(node.Left, node.Right) ?? base.VisitBinary(node); } } return base.VisitBinary(node); } protected override Expression VisitConstant(ConstantExpression node) { if (node != null && node.Type.IsGenericType && node.Type.GetGenericTypeDefinition() == typeof(MockQueryable<>)) { //var asQueryableMethod = createQueryableMethod.MakeGenericMethod(node.Type.GetGenericArguments()[0]); //return Expression.Call(null, asQueryableMethod); return this.underlyingCreateMocks; } return base.VisitConstant(node); } protected override Expression VisitMember(MemberExpression node) { if (node != null && this.stackIndex > 0 && node.Type == typeof(bool)) { return ConvertToSetup(node.Expression, node, Expression.Constant(true)); } return base.VisitMember(node); } protected override Expression VisitMethodCall(MethodCallExpression node) { if (node != null) { if (node.Method.DeclaringType == typeof(Queryable) && queryableMethods.Contains(node.Method.Name)) { this.stackIndex++; var result = base.VisitMethodCall(node); this.stackIndex--; return result; } if (unsupportedMethods.Contains(node.Method.Name)) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.LinqMethodNotSupported, node.Method.Name)); } if (this.stackIndex > 0 && node.Type == typeof(bool)) { return ConvertToSetup(node.Object, node, Expression.Constant(true)); } } return base.VisitMethodCall(node); } protected override Expression VisitUnary(UnaryExpression node) { if (node != null && this.stackIndex > 0 && node.NodeType == ExpressionType.Not) { return ConvertToSetup(node.Operand, Expression.Constant(false)) ?? base.VisitUnary(node); } return base.VisitUnary(node); } private static Expression ConvertToSetup(Expression left, Expression right) { switch (left.NodeType) { case ExpressionType.MemberAccess: var member = (MemberExpression)left; member.ThrowIfNotMockeable(); return ConvertToSetupProperty(member.Expression, member, right); case ExpressionType.Call: var method = (MethodCallExpression)left; if (!method.Method.CanOverride()) throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.LinqMethodNotVirtual, method.ToStringFixed())); return ConvertToSetup(method.Object, method, right); case ExpressionType.Invoke: var invocation = (InvocationExpression)left; if (invocation.Expression is ParameterExpression && typeof(Delegate).IsAssignableFrom(invocation.Expression.Type)) { return ConvertToSetup(invocation, right); } else { break; } case ExpressionType.Convert: var left1 = (UnaryExpression)left; return ConvertToSetup(left1.Operand, Expression.Convert(right, left1.Operand.Type)); } return null; } private static Expression ConvertToSetup(InvocationExpression invocation, Expression right) { // transforms a delegate invocation expression such as `f(...) == x` (where `invocation` := `f(...)` and `right` := `x`) // to `Mock.Get(f).Setup(f' => f'(...)).Returns(x) != null` (which in turn will get incorporated into a query // `CreateMocks().First(f => ...)`. var delegateParameter = invocation.Expression; var mockGetMethod = typeof(Mock) .GetMethod("Get", BindingFlags.Public | BindingFlags.Static) .MakeGenericMethod(delegateParameter.Type); var mockGetCall = Expression.Call(mockGetMethod, delegateParameter); var setupMethod = typeof(Mock<>) .MakeGenericType(delegateParameter.Type) .GetMethods("Setup") .Single(m => m.IsGenericMethod) .MakeGenericMethod(right.Type); var setupCall = Expression.Call( mockGetCall, setupMethod, Expression.Lambda(invocation, invocation.Expression as ParameterExpression)); var returnsMethod = typeof(IReturns<,>) .MakeGenericType(delegateParameter.Type, right.Type) .GetMethod("Returns", new[] { right.Type }); var returnsCall = Expression.Call( setupCall, returnsMethod, right); return Expression.NotEqual(returnsCall, Expression.Constant(null)); } private static Expression ConvertToSetupProperty(Expression targetObject, Expression left, Expression right) { // TODO: throw if target is a static class? var sourceType = targetObject.Type; var propertyInfo = (PropertyInfo)((MemberExpression)left).Member; var propertyType = propertyInfo.PropertyType; // where foo.Name == "bar" // becomes: // where Mock.Get(foo).SetupProperty(mock => mock.Name, "bar") != null // if the property is readonly, we can only do a Setup(...) which is the same as a method setup. if (!propertyInfo.CanWrite || propertyInfo.GetSetMethod(true).IsPrivate) return ConvertToSetup(targetObject, left, right); // This will get up to and including the Mock.Get(foo).Setup(mock => mock.Name) call. var propertySetup = VisitFluent(left); // We need to go back one level, to the target expression of the Setup call, // which would be the Mock.Get(foo), where we will actually invoke SetupProperty instead. if (propertySetup.NodeType != ExpressionType.Call) throw new NotSupportedException(string.Format(Resources.UnexpectedTranslationOfMemberAccess, propertySetup.ToStringFixed())); var propertyCall = (MethodCallExpression)propertySetup; var mockExpression = propertyCall.Object; var propertyExpression = propertyCall.Arguments.First().StripQuotes(); // We can safely just set the value here since `SetProperty` will temporarily enable auto-stubbing // if the underlying `IQueryable` provider implementation hasn't already enabled it permanently by // calling `SetupAllProperties`. // // This method also enables the use of this querying capability against plain DTO even // if their properties are not virtual. var setPropertyMethod = typeof(Mocks) .GetMethod("SetProperty", BindingFlags.Static | BindingFlags.NonPublic) .MakeGenericMethod(mockExpression.Type.GetGenericArguments().First(), propertyInfo.PropertyType); return Expression.Equal( Expression.Call(setPropertyMethod, mockExpression, propertyCall.Arguments.First(), right), Expression.Constant(true)); } private static Expression ConvertToSetup(Expression targetObject, Expression left, Expression right) { // TODO: throw if target is a static class? var sourceType = targetObject.Type; var returnType = left.Type; var returnsMethod = typeof(IReturns<,>) .MakeGenericType(sourceType, returnType) .GetMethod("Returns", new[] { returnType }); if (right is ConstantExpression constExpr && constExpr.Value == null) { right = Expression.Constant(null, left.Type); } return Expression.NotEqual( Expression.Call(VisitFluent(left), returnsMethod, right), Expression.Constant(null)); } private static Expression VisitFluent(Expression expression) { return new FluentMockVisitor(resolveRoot: p => Expression.Call(null, Mock.GetMethod.MakeGenericMethod(p.Type), p), setupRightmost: true) .Visit(expression); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.StreamAnalytics; using Microsoft.Azure.Management.StreamAnalytics.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.StreamAnalytics { public partial class StreamAnalyticsManagementClient : ServiceClient<StreamAnalyticsManagementClient>, IStreamAnalyticsManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// The URI used as the base for all Service Management requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } set { this._baseUri = value; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// When you create a Windows Azure subscription, it is uniquely /// identified by a subscription ID. The subscription ID forms part of /// the URI for every call that you make to the Service Management /// API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } set { this._credentials = value; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IInputOperations _inputs; /// <summary> /// Operations for managing the input of the stream analytics job. /// </summary> public virtual IInputOperations Inputs { get { return this._inputs; } } private IJobOperations _streamingJobs; /// <summary> /// Operations for managing the stream analytics job. /// </summary> public virtual IJobOperations StreamingJobs { get { return this._streamingJobs; } } private IOutputOperations _outputs; /// <summary> /// Operations for managing the output of the stream analytics job. /// </summary> public virtual IOutputOperations Outputs { get { return this._outputs; } } private ISubscriptionOperations _subscriptions; /// <summary> /// Operations for Azure Stream Analytics subscription information. /// </summary> public virtual ISubscriptionOperations Subscriptions { get { return this._subscriptions; } } private ITransformationOperations _transformations; /// <summary> /// Operations for managing the transformation definition of the stream /// analytics job. /// </summary> public virtual ITransformationOperations Transformations { get { return this._transformations; } } /// <summary> /// Initializes a new instance of the StreamAnalyticsManagementClient /// class. /// </summary> public StreamAnalyticsManagementClient() : base() { this._inputs = new InputOperations(this); this._streamingJobs = new JobOperations(this); this._outputs = new OutputOperations(this); this._subscriptions = new SubscriptionOperations(this); this._transformations = new TransformationOperations(this); this._apiVersion = "2015-09-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(60); } /// <summary> /// Initializes a new instance of the StreamAnalyticsManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> /// <param name='baseUri'> /// Optional. The URI used as the base for all Service Management /// requests. /// </param> public StreamAnalyticsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the StreamAnalyticsManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> public StreamAnalyticsManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the StreamAnalyticsManagementClient /// class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public StreamAnalyticsManagementClient(HttpClient httpClient) : base(httpClient) { this._inputs = new InputOperations(this); this._streamingJobs = new JobOperations(this); this._outputs = new OutputOperations(this); this._subscriptions = new SubscriptionOperations(this); this._transformations = new TransformationOperations(this); this._apiVersion = "2015-09-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(60); } /// <summary> /// Initializes a new instance of the StreamAnalyticsManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> /// <param name='baseUri'> /// Optional. The URI used as the base for all Service Management /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public StreamAnalyticsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the StreamAnalyticsManagementClient /// class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public StreamAnalyticsManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// StreamAnalyticsManagementClient instance /// </summary> /// <param name='client'> /// Instance of StreamAnalyticsManagementClient to clone to /// </param> protected override void Clone(ServiceClient<StreamAnalyticsManagementClient> client) { base.Clone(client); if (client is StreamAnalyticsManagementClient) { StreamAnalyticsManagementClient clonedClient = ((StreamAnalyticsManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent && statusCode != HttpStatusCode.NotFound && statusCode != HttpStatusCode.Conflict && statusCode != HttpStatusCode.PreconditionFailed) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResponse result = null; // Deserialize Response result = new LongRunningOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.NotFound) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.Conflict) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.PreconditionFailed) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The test result of the input or output data source. /// </returns> public async Task<DataSourceTestConnectionResponse> GetTestConnectionStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetTestConnectionStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent && statusCode != HttpStatusCode.BadRequest) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataSourceTestConnectionResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent || statusCode == HttpStatusCode.BadRequest) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataSourceTestConnectionResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); result.DataSourceTestStatus = statusInstance; } JToken errorValue = responseDoc["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = errorValue["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = errorValue["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken detailsValue = errorValue["details"]; if (detailsValue != null && detailsValue.Type != JTokenType.Null) { ErrorDetailsResponse detailsInstance = new ErrorDetailsResponse(); errorInstance.Details = detailsInstance; JToken codeValue2 = detailsValue["code"]; if (codeValue2 != null && codeValue2.Type != JTokenType.Null) { string codeInstance2 = ((string)codeValue2); detailsInstance.Code = codeInstance2; } JToken messageValue2 = detailsValue["message"]; if (messageValue2 != null && messageValue2.Type != JTokenType.Null) { string messageInstance2 = ((string)messageValue2); detailsInstance.Message = messageInstance2; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.BadRequest) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.NotFound) { result.Status = OperationStatus.Failed; } if (result.DataSourceTestStatus == DataSourceTestStatus.TestFailed) { result.Status = OperationStatus.Failed; } if (result.DataSourceTestStatus == DataSourceTestStatus.TestSucceeded) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
namespace OpenKh.Tools.EpdEditor { partial class TechControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.TechParamGBox = new System.Windows.Forms.GroupBox(); this.NumericTechniqueNumber = new System.Windows.Forms.NumericUpDown(); this.NumericSuccessRate = new System.Windows.Forms.NumericUpDown(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.AttackAttribute = new System.Windows.Forms.ComboBox(); this.AttackKind = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.TechniquePower = new System.Windows.Forms.TextBox(); this.TechParamGBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NumericTechniqueNumber)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericSuccessRate)).BeginInit(); this.SuspendLayout(); // // TechParamGBox // this.TechParamGBox.Controls.Add(this.NumericTechniqueNumber); this.TechParamGBox.Controls.Add(this.NumericSuccessRate); this.TechParamGBox.Controls.Add(this.label5); this.TechParamGBox.Controls.Add(this.label4); this.TechParamGBox.Controls.Add(this.label3); this.TechParamGBox.Controls.Add(this.AttackAttribute); this.TechParamGBox.Controls.Add(this.AttackKind); this.TechParamGBox.Controls.Add(this.label2); this.TechParamGBox.Controls.Add(this.label1); this.TechParamGBox.Controls.Add(this.TechniquePower); this.TechParamGBox.Location = new System.Drawing.Point(10, 0); this.TechParamGBox.Name = "TechParamGBox"; this.TechParamGBox.Size = new System.Drawing.Size(435, 114); this.TechParamGBox.TabIndex = 0; this.TechParamGBox.TabStop = false; this.TechParamGBox.Text = "Parameters 1"; // // NumericTechniqueNumber // this.NumericTechniqueNumber.Location = new System.Drawing.Point(124, 36); this.NumericTechniqueNumber.Maximum = new decimal(new int[] { 256, 0, 0, 0}); this.NumericTechniqueNumber.Name = "NumericTechniqueNumber"; this.NumericTechniqueNumber.Size = new System.Drawing.Size(62, 23); this.NumericTechniqueNumber.TabIndex = 7; // // NumericSuccessRate // this.NumericSuccessRate.Location = new System.Drawing.Point(264, 36); this.NumericSuccessRate.Maximum = new decimal(new int[] { 65565, 0, 0, 0}); this.NumericSuccessRate.Name = "NumericSuccessRate"; this.NumericSuccessRate.Size = new System.Drawing.Size(75, 23); this.NumericSuccessRate.TabIndex = 6; this.NumericSuccessRate.Value = new decimal(new int[] { 100, 0, 0, 0}); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(265, 19); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(74, 15); this.label5.TabIndex = 5; this.label5.Text = "Success Rate"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(265, 66); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(91, 15); this.label4.TabIndex = 5; this.label4.Text = "Attack Attribute"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(6, 66); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(68, 15); this.label3.TabIndex = 5; this.label3.Text = "Attack Kind"; // // AttackAttribute // this.AttackAttribute.FormattingEnabled = true; this.AttackAttribute.Items.AddRange(new object[] { "ATK_ATTR_NONE", "ATK_ATTR_PHYSICAL", "ATK_ATTR_FIRE", "ATK_ATTR_ICE", "ATK_ATTR_THUNDER", "ATK_ATTR_DARK", "ATK_ATTR_ZERO", "ATK_ATTR_SPECIAL", "ATK_ATTR_MAX"}); this.AttackAttribute.Location = new System.Drawing.Point(265, 84); this.AttackAttribute.Name = "AttackAttribute"; this.AttackAttribute.Size = new System.Drawing.Size(158, 23); this.AttackAttribute.TabIndex = 4; this.AttackAttribute.Text = "ATK_ATTR_NONE"; // // AttackKind // this.AttackKind.FormattingEnabled = true; this.AttackKind.Items.AddRange(new object[] { "ATK_KIND_NONE", "ATK_KIND_DMG_SMALL", "ATK_KIND_DMG_BIG", "ATK_KIND_DMG_BLOW", "ATK_KIND_DMG_TOSS", "ATK_KIND_DMG_BEAT", "ATK_KIND_DMG_FLICK", "ATK_KIND_POISON", "ATK_KIND_SLOW", "ATK_KIND_STOP", "ATK_KIND_BIND", "ATK_KIND_FAINT", "ATK_KIND_FREEZE", "ATK_KIND_BURN", "ATK_KIND_CONFUSE", "ATK_KIND_BLIND", "ATK_KIND_DEATH", "ATK_KIND_KILL", "ATK_KIND_CAPTURE", "ATK_KIND_MAGNET ", "ATK_KIND_ZEROGRAVITY", "ATK_KIND_AERO", "ATK_KIND_TORNADO", "ATK_KIND_DEGENERATOR", "ATK_KIND_WITHOUT", "ATK_KIND_EAT", "ATK_KIND_TREASURERAID", "ATK_KIND_SLEEPINGDEATH", "ATK_KIND_SLEEP", "ATK_KIND_MAGNET_MUNNY", "ATK_KIND_MAGNET_HP ", "ATK_KIND_MAGNET_FOCUS", "ATK_KIND_MINIMUM", "ATK_KIND_QUAKE", "ATK_KIND_RECOVER", "ATK_KIND_DISCOMMAND", "ATK_KIND_DISPRIZE_M", "ATK_KIND_DISPRIZE_H", "ATK_KIND_DISPRIZE_F", "ATK_KIND_DETONE", "ATK_KIND_GM_BLOW", "ATK_KIND_BLAST", "ATK_KIND_MAGNESPIRAL", "ATK_KIND_GLACIALARTS", "ATK_KIND_TRANSCENDENCE", "ATK_KIND_VENGEANCE", "ATK_KIND_MAGNEBREAKER", "ATK_KIND_MAGICIMPULSE_CF", "ATK_KIND_MAGICIMPULSE_CFB", "ATK_KIND_MAGICIMPULSE_CFBB", "ATK_KIND_DMG_RISE", "ATK_KIND_STUMBLE", "ATK_KIND_MOUNT", "ATK_KIND_IMPRISONMENT", "ATK_KIND_SLOWSTOP", "ATK_KIND_GATHERING", "ATK_KIND_EXHAUSTED"}); this.AttackKind.Location = new System.Drawing.Point(6, 84); this.AttackKind.Name = "AttackKind"; this.AttackKind.Size = new System.Drawing.Size(253, 23); this.AttackKind.TabIndex = 4; this.AttackKind.Text = "ATK_KIND_NONE"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(124, 19); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(108, 15); this.label2.TabIndex = 3; this.label2.Text = "Technique Number"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(6, 19); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(97, 15); this.label1.TabIndex = 2; this.label1.Text = "Technique Power"; // // TechniquePower // this.TechniquePower.Location = new System.Drawing.Point(4, 36); this.TechniquePower.Name = "TechniquePower"; this.TechniquePower.Size = new System.Drawing.Size(100, 23); this.TechniquePower.TabIndex = 0; this.TechniquePower.Text = "1"; // // TechControl // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.TechParamGBox); this.Name = "TechControl"; this.Size = new System.Drawing.Size(454, 118); this.TechParamGBox.ResumeLayout(false); this.TechParamGBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NumericTechniqueNumber)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NumericSuccessRate)).EndInit(); this.ResumeLayout(false); } #endregion public System.Windows.Forms.GroupBox TechParamGBox; public System.Windows.Forms.NumericUpDown NumericSuccessRate; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; public System.Windows.Forms.ComboBox AttackAttribute; public System.Windows.Forms.ComboBox AttackKind; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; public System.Windows.Forms.TextBox TechniquePower; public System.Windows.Forms.NumericUpDown NumericTechniqueNumber; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal class SymbolLoader { private NameManager _nameManager; public PredefinedMembers PredefinedMembers { get; private set; } public GlobalSymbolContext GlobalSymbolContext { get; private set; } public ErrorHandling ErrorContext { get; private set; } public SymbolTable RuntimeBinderSymbolTable { get; private set; } public SymbolLoader( GlobalSymbolContext globalSymbols, UserStringBuilder userStringBuilder, ErrorHandling errorContext ) { _nameManager = globalSymbols.GetNameManager(); PredefinedMembers = new PredefinedMembers(this); ErrorContext = errorContext; GlobalSymbolContext = globalSymbols; Debug.Assert(GlobalSymbolContext != null); } public ErrorHandling GetErrorContext() { return ErrorContext; } public GlobalSymbolContext GetGlobalSymbolContext() { return GlobalSymbolContext; } public MethodSymbol LookupInvokeMeth(AggregateSymbol pAggDel) { Debug.Assert(pAggDel.AggKind() == AggKindEnum.Delegate); for (Symbol pSym = this.LookupAggMember(GetNameManager().GetPredefName(PredefinedName.PN_INVOKE), pAggDel, symbmask_t.MASK_ALL); pSym != null; pSym = this.LookupNextSym(pSym, pAggDel, symbmask_t.MASK_ALL)) { if (pSym.IsMethodSymbol() && pSym.AsMethodSymbol().isInvoke()) { return pSym.AsMethodSymbol(); } } return null; } public NameManager GetNameManager() { return _nameManager; } public PredefinedTypes getPredefTypes() { return GlobalSymbolContext.GetPredefTypes(); } public TypeManager GetTypeManager() { return this.TypeManager; } public TypeManager TypeManager { get { return this.GlobalSymbolContext.TypeManager; } } public PredefinedMembers getPredefinedMembers() { return this.PredefinedMembers; } public BSYMMGR getBSymmgr() { return this.GlobalSymbolContext.GetGlobalSymbols(); } public SymFactory GetGlobalSymbolFactory() { return this.GlobalSymbolContext.GetGlobalSymbolFactory(); } public MiscSymFactory GetGlobalMiscSymFactory() { return this.GlobalSymbolContext.GetGlobalMiscSymFactory(); } public AggregateType GetReqPredefType(PredefinedType pt) { return GetReqPredefType(pt, true); } public AggregateType GetReqPredefType(PredefinedType pt, bool fEnsureState) { AggregateSymbol agg = GetTypeManager().GetReqPredefAgg(pt); if (agg == null) { Debug.Assert(false, "Required predef type missing"); return null; } AggregateType ats = agg.getThisType(); return ats; } public AggregateSymbol GetOptPredefAgg(PredefinedType pt) { return GetOptPredefAgg(pt, true); } public AggregateSymbol GetOptPredefAgg(PredefinedType pt, bool fEnsureState) { AggregateSymbol agg = GetTypeManager().GetOptPredefAgg(pt); return agg; } public AggregateType GetOptPredefType(PredefinedType pt) { return GetOptPredefType(pt, true); } public AggregateType GetOptPredefType(PredefinedType pt, bool fEnsureState) { AggregateSymbol agg = GetTypeManager().GetOptPredefAgg(pt); if (agg == null) return null; AggregateType ats = agg.getThisType(); return ats; } public AggregateType GetOptPredefTypeErr(PredefinedType pt, bool fEnsureState) { AggregateSymbol agg = GetTypeManager().GetOptPredefAgg(pt); if (agg == null) { getPredefTypes().ReportMissingPredefTypeError(ErrorContext, pt); return null; } AggregateType ats = agg.getThisType(); return ats; } public Symbol LookupAggMember(Name name, AggregateSymbol agg, symbmask_t mask) { return getBSymmgr().LookupAggMember(name, agg, mask); } public Symbol LookupNextSym(Symbol sym, ParentSymbol parent, symbmask_t kindmask) { return BSYMMGR.LookupNextSym(sym, parent, kindmask); } public bool isManagedType(CType type) { return type.computeManagedType(this); } // It would be nice to make this a virtual method on typeSym. public AggregateType GetAggTypeSym(CType typeSym) { Debug.Assert(typeSym != null); Debug.Assert(typeSym.IsAggregateType() || typeSym.IsTypeParameterType() || typeSym.IsArrayType() || typeSym.IsNullableType()); switch (typeSym.GetTypeKind()) { case TypeKind.TK_AggregateType: return typeSym.AsAggregateType(); case TypeKind.TK_ArrayType: return GetReqPredefType(PredefinedType.PT_ARRAY); case TypeKind.TK_TypeParameterType: return typeSym.AsTypeParameterType().GetEffectiveBaseClass(); case TypeKind.TK_NullableType: return typeSym.AsNullableType().GetAts(ErrorContext); } Debug.Assert(false, "Bad typeSym!"); return null; } public bool IsBaseInterface(CType pDerived, CType pBase) { Debug.Assert(pDerived != null); Debug.Assert(pBase != null); if (!pBase.isInterfaceType()) { return false; } if (!pDerived.IsAggregateType()) { return false; } AggregateType atsDer = pDerived.AsAggregateType(); while (atsDer != null) { TypeArray ifacesAll = atsDer.GetIfacesAll(); for (int i = 0; i < ifacesAll.Size; i++) { if (AreTypesEqualForConversion(ifacesAll.Item(i), pBase)) { return true; } } atsDer = atsDer.GetBaseClass(); } return false; } public bool IsBaseClassOfClass(CType pDerived, CType pBase) { Debug.Assert(pDerived != null); Debug.Assert(pBase != null); // This checks to see whether derived is a class, and if so, // if base is a base class of derived. if (!pDerived.isClassType()) { return false; } return IsBaseClass(pDerived, pBase); } public bool IsBaseClass(CType pDerived, CType pBase) { Debug.Assert(pDerived != null); Debug.Assert(pBase != null); // A base class has got to be a class. The derived type might be a struct. if (!pBase.isClassType()) { return false; } if (pDerived.IsNullableType()) { pDerived = pDerived.AsNullableType().GetAts(ErrorContext); if (pDerived == null) { return false; } } if (!pDerived.IsAggregateType()) { return false; } AggregateType atsDer = pDerived.AsAggregateType(); AggregateType atsBase = pBase.AsAggregateType(); AggregateType atsCur = atsDer.GetBaseClass(); while (atsCur != null) { if (atsCur == atsBase) { return true; } atsCur = atsCur.GetBaseClass(); } return false; } private bool HasCovariantArrayConversion(ArrayType pSource, ArrayType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. return (pSource.rank == pDest.rank) && HasImplicitReferenceConversion(pSource.GetElementType(), pDest.GetElementType()); } public bool HasIdentityOrImplicitReferenceConversion(CType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); if (AreTypesEqualForConversion(pSource, pDest)) { return true; } return HasImplicitReferenceConversion(pSource, pDest); } protected bool AreTypesEqualForConversion(CType pType1, CType pType2) { return pType1.Equals(pType2); } private bool HasArrayConversionToInterface(ArrayType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); if (pSource.rank != 1) { return false; } if (!pDest.isInterfaceType()) { return false; } // * From a single-dimensional array type S[] to IList<T> or IReadOnlyList<T> and their base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. // We only have six interfaces to check. IList<T>, IReadOnlyList<T> and their bases: // * The base interface of IList<T> is ICollection<T>. // * The base interface of ICollection<T> is IEnumerable<T>. // * The base interface of IEnumerable<T> is IEnumerable. // * The base interface of IReadOnlyList<T> is IReadOnlyCollection<T>. // * The base interface of IReadOnlyCollection<T> is IEnumerable<T>. if (pDest.isPredefType(PredefinedType.PT_IENUMERABLE)) { return true; } AggregateType atsDest = pDest.AsAggregateType(); AggregateSymbol aggDest = pDest.getAggregate(); if (!aggDest.isPredefAgg(PredefinedType.PT_G_ILIST) && !aggDest.isPredefAgg(PredefinedType.PT_G_ICOLLECTION) && !aggDest.isPredefAgg(PredefinedType.PT_G_IENUMERABLE) && !aggDest.isPredefAgg(PredefinedType.PT_G_IREADONLYCOLLECTION) && !aggDest.isPredefAgg(PredefinedType.PT_G_IREADONLYLIST)) { return false; } Debug.Assert(atsDest.GetTypeArgsAll().Size == 1); CType pSourceElement = pSource.GetElementType(); CType pDestTypeArgument = atsDest.GetTypeArgsAll().Item(0); return HasIdentityOrImplicitReferenceConversion(pSourceElement, pDestTypeArgument); } public bool HasImplicitReferenceConversion(CType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); // The implicit reference conversions are: // * From any reference type to Object. if (pSource.IsRefType() && pDest.isPredefType(PredefinedType.PT_OBJECT)) { return true; } // * From any class type S to any class type T provided S is derived from T. if (pSource.isClassType() && pDest.isClassType() && IsBaseClass(pSource, pDest)) { return true; } // ORIGINAL RULES: // // * From any class type S to any interface type T provided S implements T. // if (pSource.isClassType() && pDest.isInterfaceType() && IsBaseInterface(pSource, pDest)) // { // return true; // } // // * from any interface type S to any interface type T, provided S is derived from T. // if (pSource.isInterfaceType() && pDest.isInterfaceType() && IsBaseInterface(pSource, pDest)) // { // return true; // } // VARIANCE EXTENSIONS: // * From any class type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S is not T and S is // an interface convertible to T. if (pSource.isClassType() && pDest.isInterfaceType() && HasAnyBaseInterfaceConversion(pSource, pDest)) { return true; } if (pSource.isInterfaceType() && pDest.isInterfaceType() && HasAnyBaseInterfaceConversion(pSource, pDest)) { return true; } if (pSource.isInterfaceType() && pDest.isInterfaceType() && pSource != pDest && HasInterfaceConversion(pSource.AsAggregateType(), pDest.AsAggregateType())) { return true; } // * From an array type S with an element type SE to an array type T with element type TE // provided that all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. if (pSource.IsArrayType() && pDest.IsArrayType() && HasCovariantArrayConversion(pSource.AsArrayType(), pDest.AsArrayType())) { return true; } // * From any array type to System.Array or any interface implemented by System.Array. if (pSource.IsArrayType() && (pDest.isPredefType(PredefinedType.PT_ARRAY) || IsBaseInterface(GetReqPredefType(PredefinedType.PT_ARRAY, false), pDest))) { return true; } // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. if (pSource.IsArrayType() && HasArrayConversionToInterface(pSource.AsArrayType(), pDest)) { return true; } // * From any delegate type to System.Delegate // // SPEC OMISSION: // // The spec should actually say // // * From any delegate type to System.Delegate // * From any delegate type to System.MulticastDelegate // * From any delegate type to any interface implemented by System.MulticastDelegate if (pSource.isDelegateType() && (pDest.isPredefType(PredefinedType.PT_MULTIDEL) || pDest.isPredefType(PredefinedType.PT_DELEGATE) || IsBaseInterface(GetReqPredefType(PredefinedType.PT_MULTIDEL, false), pDest))) { return true; } // VARIANCE EXTENSION: // * From any delegate type S to a delegate type T provided S is not T and // S is a delegate convertible to T if (pSource.isDelegateType() && pDest.isDelegateType() && HasDelegateConversion(pSource.AsAggregateType(), pDest.AsAggregateType())) { return true; } // * From the null literal to any reference type // NOTE: We extend the specification here. The C# 3.0 spec does not describe // a "null type". Rather, it says that the null literal is typeless, and is // convertible to any reference or nullable type. However, the C# 2.0 and 3.0 // implementations have a "null type" which some expressions other than the // null literal may have. (For example, (null??null), which is also an // extension to the specification.) if (pSource.IsNullType() && pDest.IsRefType()) { return true; } if (pSource.IsNullType() && pDest.IsNullableType()) { return true; } // * Implicit conversions involving type parameters that are known to be reference types. if (pSource.IsTypeParameterType() && HasImplicitReferenceTypeParameterConversion(pSource.AsTypeParameterType(), pDest)) { return true; } return false; } private bool HasImplicitReferenceTypeParameterConversion( TypeParameterType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); if (!pSource.IsRefType()) { // Not a reference conversion. return false; } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. AggregateType pEBC = pSource.GetEffectiveBaseClass(); if (pDest == pEBC) { return true; } // * From T to any base class of C. if (IsBaseClass(pEBC, pDest)) { return true; } // * From T to any interface implemented by C. if (IsBaseInterface(pEBC, pDest)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I. TypeArray pInterfaces = pSource.GetInterfaceBounds(); for (int i = 0; i < pInterfaces.Size; ++i) { if (pInterfaces.Item(i) == pDest) { return true; } } // * From T to a type parameter U, provided T depends on U. if (pDest.IsTypeParameterType() && pSource.DependsOn(pDest.AsTypeParameterType())) { return true; } return false; } private bool HasAnyBaseInterfaceConversion(CType pDerived, CType pBase) { if (!pBase.isInterfaceType()) { return false; } if (!pDerived.IsAggregateType()) { return false; } AggregateType atsDer = pDerived.AsAggregateType(); while (atsDer != null) { TypeArray ifacesAll = atsDer.GetIfacesAll(); for (int i = 0; i < ifacesAll.size; i++) { if (HasInterfaceConversion(ifacesAll.Item(i).AsAggregateType(), pBase.AsAggregateType())) { return true; } } atsDer = atsDer.GetBaseClass(); } return false; } //////////////////////////////////////////////////////////////////////////////// // The rules for variant interface and delegate conversions are the same: // // An interface/delegate type S is convertible to an interface/delegate type T // if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all // parameters of U: // // * if the ith parameter of U is invariant then Si is exactly equal to Ti. // * if the ith parameter of U is covariant then either Si is exactly equal // to Ti, or there is an implicit reference conversion from Si to Ti. // * if the ith parameter of U is contravariant then either Si is exactly // equal to Ti, or there is an implicit reference conversion from Ti to Si. private bool HasInterfaceConversion(AggregateType pSource, AggregateType pDest) { Debug.Assert(pSource != null && pSource.isInterfaceType()); Debug.Assert(pDest != null && pDest.isInterfaceType()); return HasVariantConversion(pSource, pDest); } ////////////////////////////////////////////////////////////////////////////// private bool HasDelegateConversion(AggregateType pSource, AggregateType pDest) { Debug.Assert(pSource != null && pSource.isDelegateType()); Debug.Assert(pDest != null && pDest.isDelegateType()); return HasVariantConversion(pSource, pDest); } ////////////////////////////////////////////////////////////////////////////// private bool HasVariantConversion(AggregateType pSource, AggregateType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); if (pSource == pDest) { return true; } AggregateSymbol pAggSym = pSource.getAggregate(); if (pAggSym != pDest.getAggregate()) { return false; } TypeArray pTypeParams = pAggSym.GetTypeVarsAll(); TypeArray pSourceArgs = pSource.GetTypeArgsAll(); TypeArray pDestArgs = pDest.GetTypeArgsAll(); Debug.Assert(pTypeParams.size == pSourceArgs.size); Debug.Assert(pTypeParams.size == pDestArgs.size); for (int iParam = 0; iParam < pTypeParams.size; ++iParam) { CType pSourceArg = pSourceArgs.Item(iParam); CType pDestArg = pDestArgs.Item(iParam); // If they're identical then this one is automatically good, so skip it. if (pSourceArg == pDestArg) { continue; } TypeParameterType pParam = pTypeParams.Item(iParam).AsTypeParameterType(); if (pParam.Invariant) { return false; } if (pParam.Covariant) { if (!HasImplicitReferenceConversion(pSourceArg, pDestArg)) { return false; } } if (pParam.Contravariant) { if (!HasImplicitReferenceConversion(pDestArg, pSourceArg)) { return false; } } } return true; } private bool HasImplicitBoxingTypeParameterConversion( TypeParameterType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); if (pSource.IsRefType()) { // Not a boxing conversion; both source and destination are references. return false; } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. AggregateType pEBC = pSource.GetEffectiveBaseClass(); if (pDest == pEBC) { return true; } // * From T to any base class of C. if (IsBaseClass(pEBC, pDest)) { return true; } // * From T to any interface implemented by C. if (IsBaseInterface(pEBC, pDest)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I. TypeArray pInterfaces = pSource.GetInterfaceBounds(); for (int i = 0; i < pInterfaces.Size; ++i) { if (pInterfaces.Item(i) == pDest) { return true; } } // * The conversion from T to a type parameter U, provided T depends on U, is not // classified as a boxing conversion because it is not guaranteed to box. // (If both T and U are value types then it is an identity conversion.) return false; } private bool HasImplicitTypeParameterBaseConversion( TypeParameterType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); if (HasImplicitReferenceTypeParameterConversion(pSource, pDest)) { return true; } if (HasImplicitBoxingTypeParameterConversion(pSource, pDest)) { return true; } if (pDest.IsTypeParameterType() && pSource.DependsOn(pDest.AsTypeParameterType())) { return true; } return false; } public bool HasImplicitBoxingConversion(CType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); // Certain type parameter conversions are classified as boxing conversions. if (pSource.IsTypeParameterType() && HasImplicitBoxingTypeParameterConversion(pSource.AsTypeParameterType(), pDest)) { return true; } // The rest of the boxing conversions only operate when going from a value type // to a reference type. if (!pSource.IsValType() || !pDest.IsRefType()) { return false; } // A boxing conversion exists from a nullable type to a reference type // if and only if a boxing conversion exists from the underlying type. if (pSource.IsNullableType()) { return HasImplicitBoxingConversion(pSource.AsNullableType().GetUnderlyingType(), pDest); } // A boxing conversion exists from any non-nullable value type to object, // to System.ValueType, and to any interface type implemented by the // non-nullable value type. Furthermore, an enum type can be converted // to the type System.Enum. // We set the base class of the structs to System.ValueType, System.Enum, etc, // so we can just check here. if (IsBaseClass(pSource, pDest)) { return true; } if (HasAnyBaseInterfaceConversion(pSource, pDest)) { return true; } return false; } public bool HasBaseConversion(CType pSource, CType pDest) { // By a "base conversion" we mean: // // * an identity conversion // * an implicit reference conversion // * an implicit boxing conversion // * an implicit type parameter conversion // // In other words, these are conversions that can be made to a base // class, base interface or co/contravariant type without any change in // representation other than boxing. A conversion from, say, int to double, // is NOT a "base conversion", because representation is changed. A conversion // from, say, lambda to expression tree is not a "base conversion" because // do not have a type. // // The existence of a base conversion depends solely upon the source and // destination types, not the source expression. // // This notion is not found in the spec but it is useful in the implementation. if (pSource.IsAggregateType() && pDest.isPredefType(PredefinedType.PT_OBJECT)) { // If we are going from any aggregate type (class, struct, interface, enum or delegate) // to object, we immediately return true. This may seem like a mere optimization -- // after all, if we have an aggregate then we have some kind of implicit conversion // to object. // // However, it is not a mere optimization; this introduces a control flow change // in error reporting scenarios for unresolved type forwarders. If a type forwarder // cannot be resolved then the resulting type symbol will be an aggregate, but // we will not be able to classify it into class, struct, etc. // // We know that we will have an error in this case; we do not wish to compound // that error by giving a spurious "you cannot convert this thing to object" // error, which, after all, will go away when the type forwarding problem is // fixed. return true; } if (HasIdentityOrImplicitReferenceConversion(pSource, pDest)) { return true; } if (HasImplicitBoxingConversion(pSource, pDest)) { return true; } if (pSource.IsTypeParameterType() && HasImplicitTypeParameterBaseConversion(pSource.AsTypeParameterType(), pDest)) { return true; } return false; } public bool FCanLift() { return null != GetOptPredefAgg(PredefinedType.PT_G_OPTIONAL, false); } public bool IsBaseAggregate(AggregateSymbol derived, AggregateSymbol @base) { Debug.Assert(!derived.IsEnum() && !@base.IsEnum()); if (derived == @base) return true; // identity. // refactoring error tolerance: structs and delegates can be base classes in error scenarios so // we cannot filter on whether or not the base is marked as sealed. if (@base.IsInterface()) { // Search the direct and indirect interfaces via ifacesAll, going up the base chain... while (derived != null) { for (int i = 0; i < derived.GetIfacesAll().Size; i++) { AggregateType iface = derived.GetIfacesAll().Item(i).AsAggregateType(); if (iface.getAggregate() == @base) return true; } derived = derived.GetBaseAgg(); } return false; } // base is a class. Just go up the base class chain to look for it. while (derived.GetBaseClass() != null) { derived = derived.GetBaseClass().getAggregate(); if (derived == @base) return true; } return false; } internal void SetSymbolTable(SymbolTable symbolTable) { RuntimeBinderSymbolTable = symbolTable; } } }
namespace Nancy.Tests.Unit { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using FakeItEasy; using Nancy.Bootstrapper; using Nancy.Diagnostics; using Nancy.ErrorHandling; using Nancy.Extensions; using Nancy.Helpers; using Nancy.Routing; using Nancy.Tests.Fakes; using Xunit; using Nancy.Responses.Negotiation; public class NancyEngineFixture { private readonly INancyEngine engine; private readonly IRouteResolver resolver; private readonly FakeRoute route; private readonly NancyContext context; private readonly INancyContextFactory contextFactory; private readonly Response response; private readonly IStatusCodeHandler statusCodeHandler; private readonly IRouteInvoker routeInvoker; private readonly IRequestDispatcher requestDispatcher; private readonly IResponseNegotiator negotiator; public NancyEngineFixture() { this.resolver = A.Fake<IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); this.statusCodeHandler = A.Fake<IStatusCodeHandler>(); this.requestDispatcher = A.Fake<IRequestDispatcher>(); this.negotiator = A.Fake<IResponseNegotiator>(); A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._, A<CancellationToken>._)) .Returns(CreateResponseTask(new Response())); A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false); contextFactory = A.Fake<INancyContextFactory>(); A.CallTo(() => contextFactory.Create(A<Request>._)).Returns(context); var resolveResult = new ResolveResult { Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null }; A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolveResult); var applicationPipelines = new Pipelines(); this.routeInvoker = A.Fake<IRouteInvoker>(); A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._)).ReturnsLazily(arg => { return ((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1], A<CancellationToken>._).Result; }); this.engine = new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator) { RequestPipelinesFactory = ctx => applicationPipelines }; } [Fact] public void Should_throw_argumentnullexception_when_created_with_null_dispatcher() { // Given, When var exception = Record.Exception(() => new NancyEngine(null, A.Fake<INancyContextFactory>(), new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator)); // Then exception.ShouldBeOfType<ArgumentNullException>(); } [Fact] public void Should_throw_argumentnullexception_when_created_with_null_context_factory() { // Given, When var exception = Record.Exception(() => new NancyEngine(this.requestDispatcher, null, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator)); // Then exception.ShouldBeOfType<ArgumentNullException>(); } [Fact] public void Should_throw_argumentnullexception_when_created_with_null_status_handler() { // Given, When var exception = Record.Exception(() => new NancyEngine(this.requestDispatcher, A.Fake<INancyContextFactory>(), null, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator)); // Then exception.ShouldBeOfType<ArgumentNullException>(); } [Fact] public void HandleRequest_Should_Throw_ArgumentNullException_When_Given_A_Null_Request() { // Given, Request request = null; // When var exception = Record.Exception(() => engine.HandleRequest(request)); // Then exception.ShouldBeOfType<ArgumentNullException>(); } [Fact] public void HandleRequest_should_get_context_from_context_factory() { // Given var request = new Request("GET", "/", "http"); // When this.engine.HandleRequest(request); // Then A.CallTo(() => this.contextFactory.Create(request)).MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void HandleRequest_should_set_correct_response_on_returned_context() { // Given var request = new Request("GET", "/", "http"); A.CallTo(() => this.requestDispatcher.Dispatch(this.context, A<CancellationToken>._)) .Returns(CreateResponseTask(this.response)); // When var result = this.engine.HandleRequest(request); // Then result.Response.ShouldBeSameAs(this.response); } [Fact] public void Should_not_add_nancy_version_number_header_on_returned_response() { // NOTE: Regression for removal of nancy-version from response headers // Given var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); // Then result.Response.Headers.ContainsKey("Nancy-Version").ShouldBeFalse(); } [Fact] public void Should_not_throw_exception_when_handlerequest_is_invoked_and_pre_request_hook_is_null() { // Given var pipelines = new Pipelines { BeforeRequest = null }; engine.RequestPipelinesFactory = (ctx) => pipelines; // When var request = new Request("GET", "/", "http"); // Then this.engine.HandleRequest(request); } [Fact] public void Should_not_throw_exception_when_handlerequest_is_invoked_and_post_request_hook_is_null() { // Given var pipelines = new Pipelines { AfterRequest = null }; engine.RequestPipelinesFactory = (ctx) => pipelines; // When var request = new Request("GET", "/", "http"); // Then this.engine.HandleRequest(request); } [Fact] public void Should_call_pre_request_hook_should_be_invoked_with_request_from_context() { // Given Request passedRequest = null; var pipelines = new Pipelines(); pipelines.BeforeRequest.AddItemToStartOfPipeline((ctx) => { passedRequest = ctx.Request; return null; }); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); this.context.Request = request; // When this.engine.HandleRequest(request); // Then passedRequest.ShouldBeSameAs(request); } [Fact] public void Should_return_response_from_pre_request_hook_when_not_null() { // Given var returnedResponse = A.Fake<Response>(); var pipelines = new Pipelines(); pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => returnedResponse); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); // Then result.Response.ShouldBeSameAs(returnedResponse); } [Fact] public void Should_allow_post_request_hook_to_modify_context_items() { // Given var pipelines = new Pipelines(); pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => { ctx.Items.Add("PostReqTest", new object()); return null; }); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); // Then result.Items.ContainsKey("PostReqTest").ShouldBeTrue(); } [Fact] public void Should_allow_post_request_hook_to_replace_response() { // Given var newResponse = new Response(); var pipelines = new Pipelines(); pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => ctx.Response = newResponse); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); // Then result.Response.ShouldBeSameAs(newResponse); } [Fact] public void HandleRequest_prereq_returns_response_should_still_run_postreq() { // Given var returnedResponse = A.Fake<Response>(); var postReqCalled = false; var pipelines = new Pipelines(); pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => returnedResponse); pipelines.AfterRequest.AddItemToEndOfPipeline(ctx => postReqCalled = true); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When this.engine.HandleRequest(request); // Then postReqCalled.ShouldBeTrue(); } [Fact] public void Should_ask_status_handler_if_it_can_handle_status_code() { // Given var request = new Request("GET", "/", "http"); // When this.engine.HandleRequest(request); // Then A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_not_invoke_status_handler_if_not_supported_status_code() { // Given var request = new Request("GET", "/", "http"); // When this.engine.HandleRequest(request); // Then A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustNotHaveHappened(); } [Fact] public void Should_invoke_status_handler_if_supported_status_code() { // Given var request = new Request("GET", "/", "http"); A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(true); // When this.engine.HandleRequest(request); // Then A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_set_status_code_to_500_if_route_throws() { // Given var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(new NotImplementedException())); var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); // Then result.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError); } [Fact] public void Should_store_exception_details_if_dispatcher_throws() { // Given var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(new NotImplementedException())); var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); // Then result.GetExceptionDetails().ShouldContain("NotImplementedException"); } [Fact] public void Should_invoke_the_error_request_hook_if_one_exists_when_dispatcher_throws() { // Given var testEx = new Exception(); var errorRoute = new Route("GET", "/", null, (x,c) => { throw testEx; }); var resolvedRoute = new ResolveResult( errorRoute, DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(testEx)); Exception handledException = null; NancyContext handledContext = null; var errorResponse = new Response(); A.CallTo(() => this.negotiator.NegotiateResponse(A<object>.Ignored, A<NancyContext>.Ignored)) .Returns(errorResponse); Func<NancyContext, Exception, dynamic> routeErrorHook = (ctx, ex) => { handledContext = ctx; handledException = ex; return errorResponse; }; var pipelines = new Pipelines(); pipelines.OnError.AddItemToStartOfPipeline(routeErrorHook); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); // Then Assert.Equal(testEx, handledException); Assert.Equal(result, handledContext); Assert.Equal(result.Response, errorResponse); } [Fact] public void Should_add_unhandled_exception_to_context_as_requestexecutionexception() { // Given var routeUnderTest = new Route("GET", "/", null, (x,c) => { throw new Exception(); }); var resolved = new ResolveResult(routeUnderTest, DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolved); A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._)) .Invokes((x) => routeUnderTest.Action.Invoke(DynamicDictionary.Empty, new CancellationToken())); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(new Exception())); var pipelines = new Pipelines(); pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); // Then result.Items.Keys.Contains("ERROR_EXCEPTION").ShouldBeTrue(); result.Items["ERROR_EXCEPTION"].ShouldBeOfType<RequestExecutionException>(); } [Fact] public void Should_persist_original_exception_in_requestexecutionexception() { // Given var expectedException = new Exception(); var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(expectedException)); var pipelines = new Pipelines(); pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException; // Then returnedException.InnerException.ShouldBeSameAs(expectedException); } [Fact] public void Should_persist_and_unwrap_original_exception_in_requestexecutionexception() { // Given var expectedException = new Exception(); var aggregateException = new AggregateException(expectedException); var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(aggregateException)); var pipelines = new Pipelines(); pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException; // Then returnedException.InnerException.ShouldBeSameAs(expectedException); } [Fact] public void Should_persist_and_unwrap_nested_original_exception_in_requestexecutionexception() { // Given var expectedException = new Exception(); var expectedExceptionInner = new AggregateException(expectedException); var aggregateExceptionOuter = new AggregateException(expectedExceptionInner); var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(aggregateExceptionOuter)); var pipelines = new Pipelines(); pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException; // Then returnedException.InnerException.ShouldBeSameAs(expectedException); } [Fact] public void Should_persist_and_unwrap_multiple_nested_original_exception_in_requestexecutionexception() { // Given var expectedException1 = new Exception(); var expectedException2 = new Exception(); var expectedException3 = new Exception(); var exceptionsList = new List<Exception>() { expectedException1, expectedException2, expectedException3 }; var aggregateExceptionInner = new AggregateException(exceptionsList); var aggregateExceptionOuter = new AggregateException(aggregateExceptionInner); var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(aggregateExceptionOuter)); var pipelines = new Pipelines(); pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException; // Then var returnedInnerException = returnedException.InnerException as AggregateException; returnedInnerException.ShouldBeOfType(typeof(AggregateException)); Assert.Equal(exceptionsList.Count, returnedInnerException.InnerExceptions.Count); } [Fact] public void Should_persist_and_unwrap_multiple_nested_original_exception_in_requestexecutionexception_with_exceptions_on_multiple_levels() { // Given var expectedException1 = new Exception(); var expectedException2 = new Exception(); var expectedException3 = new Exception(); var expectedException4 = new Exception(); var expectgedInnerExceptions = 4; var exceptionsListInner = new List<Exception>() { expectedException1, expectedException2, expectedException3 }; var expectedExceptionInner = new AggregateException(exceptionsListInner); var exceptionsListOuter = new List<Exception>() { expectedExceptionInner, expectedException4 }; var aggregateExceptionOuter = new AggregateException(exceptionsListOuter); var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(aggregateExceptionOuter)); var pipelines = new Pipelines(); pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException; // Then var returnedInnerException = returnedException.InnerException as AggregateException; returnedInnerException.ShouldBeOfType(typeof(AggregateException)); Assert.Equal(expectgedInnerExceptions, returnedInnerException.InnerExceptions.Count); } [Fact] public void Should_add_requestexecutionexception_to_context_when_pipeline_is_null() { // Given var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(new Exception())); var pipelines = new Pipelines { OnError = null }; engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); // Then result.Items.Keys.Contains("ERROR_EXCEPTION").ShouldBeTrue(); result.Items["ERROR_EXCEPTION"].ShouldBeOfType<RequestExecutionException>(); } [Fact] public void Should_persist_original_exception_in_requestexecutionexception_when_pipeline_is_null() { // Given var expectedException = new Exception(); var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(expectedException)); var pipelines = new Pipelines { OnError = null }; engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException; // Then returnedException.InnerException.ShouldBeSameAs(expectedException); } [Fact] public void Should_return_static_content_response_if_one_returned() { var localResponse = new Response(); var staticContent = A.Fake<IStaticContentProvider>(); A.CallTo(() => staticContent.GetContent(A<NancyContext>._)) .Returns(localResponse); var localEngine = new NancyEngine( this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), staticContent, this.negotiator); var request = new Request("GET", "/", "http"); var result = localEngine.HandleRequest(request); result.Response.ShouldBeSameAs(localResponse); } [Fact] public void Should_set_status_code_to_500_if_pre_execute_response_throws() { // Given var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetCompletedTask<Response>(new PreExecuteFailureResponse())); var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); // Then result.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError); } [Fact] public void Should_throw_operationcancelledexception_when_disposed_handling_request() { // Given var request = new Request("GET", "/", "http"); var engine = new NancyEngine(A.Fake<IRequestDispatcher>(), A.Fake<INancyContextFactory>(), new[] {this.statusCodeHandler}, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator); engine.Dispose(); // When var exception = Record.Exception(() => engine.HandleRequest(request)); // Then exception.ShouldBeOfType<OperationCanceledException>(); } private static Task<Response> CreateResponseTask(Response response) { var tcs = new TaskCompletionSource<Response>(); tcs.SetResult(response); return tcs.Task; } } public class PreExecuteFailureResponse : Response { public override Task PreExecute(NancyContext context) { return TaskHelpers.GetFaultedTask<object>(new InvalidOperationException()); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime { using System; using System.Collections.Generic; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Array), NoConstructors=true)] public class ArrayImpl { // // State // [TS.WellKnownField( "ArrayImpl_m_numElements" )] internal uint m_numElements; // // Constructor Methods // private ArrayImpl() { m_numElements = 0; } //--// // // Helper Methods // public int GetUpperBound( int dimension ) { TS.VTable vTable = TS.VTable.Get( this ); TS.TypeRepresentation ts = vTable.TypeInfo; if(ts is TS.SzArrayReferenceTypeRepresentation) { return (int)(m_numElements - 1); } TS.MultiArrayReferenceTypeRepresentation ts2 = (TS.MultiArrayReferenceTypeRepresentation)ts; return (int)ts2.Dimensions[dimension].m_upperBound; } public int GetLowerBound( int dimension ) { TS.VTable vTable = TS.VTable.Get( this ); TS.TypeRepresentation ts = vTable.TypeInfo; if(ts is TS.SzArrayReferenceTypeRepresentation) { return 0; } TS.MultiArrayReferenceTypeRepresentation ts2 = (TS.MultiArrayReferenceTypeRepresentation)ts; return (int)ts2.Dimensions[dimension].m_lowerBound; } public static unsafe void Clear( ArrayImpl array , int index , int length ) { if(index < 0 || length < 0 ) { throw new IndexOutOfRangeException(); } int indexEnd = index + length; if(indexEnd > array.Length) { throw new IndexOutOfRangeException(); } TS.VTable vTable = TS.VTable.Get( array ); void* voidPtr = array.GetPointerToElement( (uint)index ); void* voidPtrEnd = array.GetPointerToElement( (uint)indexEnd ); if((vTable.ElementSize & 3) == 0) { // // Word aligned. // uint* ptr = (uint*)voidPtr; uint* ptrEnd = (uint*)voidPtrEnd; while(ptr < ptrEnd) { *ptr++ = 0; } } else { byte* ptr = (byte*)voidPtr; byte* ptrEnd = (byte*)voidPtrEnd; while(ptr < ptrEnd) { *ptr++ = 0; } } } internal static unsafe void Copy( ArrayImpl sourceArray , int sourceIndex , ArrayImpl destinationArray , int destinationIndex , int length , bool reliable ) { if(sourceIndex < 0 || destinationIndex < 0 || length < 0 ) { throw new IndexOutOfRangeException(); } int sourceIndexEnd = sourceIndex + length; if(sourceIndexEnd > sourceArray.Length) { throw new IndexOutOfRangeException(); } int destinationIndexEnd = destinationIndex + length; if(destinationIndexEnd > destinationArray.Length) { throw new IndexOutOfRangeException(); } TS.VTable vTableSource = TS.VTable.Get( sourceArray ); TS.VTable vTableDestination = TS.VTable.Get( destinationArray ); if(vTableSource != vTableDestination) { throw new NotSupportedException(); } void* voidSourcePtr = sourceArray .GetPointerToElement( (uint)sourceIndex ); void* voidDestinationPtr = destinationArray.GetPointerToElement( (uint)destinationIndex ); if(voidSourcePtr != voidDestinationPtr) { BufferImpl.InternalMemoryMove( (byte*)voidSourcePtr, (byte*)voidDestinationPtr, length * (int)vTableSource.ElementSize ); } } //--// // // This is used to cast between an object and and ArrayImpl, which is not possible in C#. // [TS.GenerateUnsafeCast] public extern static ArrayImpl CastAsArray( object target ); // // This is used to cast between an object and and ArrayImpl, which is not possible in C#. // [TS.GenerateUnsafeCast] public extern Array CastThisAsArray(); // // This is used to get the pointer to the data, which is not possible in C#. // [Inline] public unsafe uint* GetDataPointer() { fixed(uint* ptr = &m_numElements) { return &ptr[1]; } } // // This is used to get the pointer to the data, which is not possible in C#. // public unsafe void* GetPointerToElement( uint index ) { byte* ptr = (byte*)GetDataPointer(); return &ptr[index * this.ElementSize]; } // // This is used to get the pointer to the data, which is not possible in C#. // public unsafe uint* GetEndDataPointer() { return (uint*)GetPointerToElement( m_numElements ); } //--// internal void SetLength( uint numElements ) { m_numElements = numElements; } //--// [NoInline] internal static void Throw_FixedSizeCollection() { #if EXCEPTION_STRINGS throw new NotSupportedException( "NotSupported_FixedSizeCollection" ); #else throw new NotSupportedException(); #endif } [NoInline] internal static void Throw_ReadOnlyCollection() { #if EXCEPTION_STRINGS throw new NotSupportedException( "NotSupported_ReadOnlyCollection" ); #else throw new NotSupportedException(); #endif } [NoInline] internal static void EnsureSZArray( Array array ) { if(array != null && array.Rank != 1) { #if EXCEPTION_STRINGS throw new ArgumentException( "Rank_MultiDimNotSupported" ); #else throw new ArgumentException(); #endif } } // //--// // // Access Methods // public int Length { [Inline] [TS.WellKnownMethod( "ArrayImpl_get_Length" )] get { return (int)m_numElements; } } public uint Size { [Inline] get { return m_numElements * this.ElementSize; } } public uint ElementSize { [Inline] get { return TS.VTable.Get( this ).ElementSize; } } public int Rank { get { TS.VTable vTable = TS.VTable.Get( this ); TS.TypeRepresentation ts = vTable.TypeInfo; if(ts is TS.SzArrayReferenceTypeRepresentation) { return 1; } TS.MultiArrayReferenceTypeRepresentation ts2 = (TS.MultiArrayReferenceTypeRepresentation)ts; return (int)ts2.Dimensions.Length; } } } //---------------------------------------------------------------------------------------- // ! READ THIS BEFORE YOU WORK ON THIS CLASS. // // This class is needed to allow an SZ array of type T[] to expose IList<T>, // IList<T.BaseType>, etc., etc. all the way up to IList<Object>. When the following call is // made: // // ((IList<T>) (new U[n])).SomeIListMethod() // // the interface stub dispatcher treats this as a special case, loads up SZArrayHelper, // finds the corresponding generic method (matched simply by method name), instantiates // it for type <T> and executes it. // // The "T" will reflect the interface used to invoke the method. The actual runtime "this" will be // array that is castable to "T[]" (i.e. for primitivs and valuetypes, it will be exactly // "T[]" - for orefs, it may be a "U[]" where U derives from T.) //---------------------------------------------------------------------------------------- [TS.WellKnownType( "Microsoft_Zelig_Runtime_SZArrayHelper" )] static class SZArrayHelper<T> { // ----------------------------------------------------------- // ------- Implement IEnumerable<T> interface methods -------- // ----------------------------------------------------------- [Inline] internal static IEnumerator<T> GetEnumerator( T[] _this ) { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! return new SZGenericArrayEnumerator( _this ); } // ----------------------------------------------------------- // ------- Implement ICollection<T> interface methods -------- // ----------------------------------------------------------- [Inline] internal static void CopyTo( T[] _this , T[] array , int index ) { ArrayImpl.EnsureSZArray( array ); Array.Copy( _this, 0, array, index, _this.Length ); } [Inline] internal static int get_Count( T[] _this ) { return _this.Length; } // ----------------------------------------------------------- // ---------- Implement IList<T> interface methods ----------- // ----------------------------------------------------------- [Inline] internal static T get_Item( T[] _this , int index ) { //// if((uint)index >= (uint)_this.Length) //// { //// ThrowHelper.ThrowArgumentOutOfRangeException(); //// } return _this[index]; } [Inline] internal static void set_Item( T[] _this , int index , T value ) { //// if((uint)index >= (uint)_this.Length) //// { //// ThrowHelper.ThrowArgumentOutOfRangeException(); //// } _this[index] = value; } [Inline] internal static void Add( T[] _this , T value ) { ArrayImpl.Throw_FixedSizeCollection(); } [Inline] internal static bool Contains( T[] _this , T value ) { return Array.IndexOf( _this, value ) != -1; } [Inline] internal static bool get_IsReadOnly( T[] _this ) { return true; } [Inline] internal static void Clear( T[] _this ) { ArrayImpl.Throw_ReadOnlyCollection(); } [Inline] internal static int IndexOf( T[] _this , T value ) { return Array.IndexOf( _this, value ); } [Inline] internal static void Insert( T[] _this , int index , T value ) { // Not meaningful for arrays ArrayImpl.Throw_FixedSizeCollection(); } [Inline] internal static bool Remove( T[] _this , T value ) { // Not meaningful for arrays ArrayImpl.Throw_FixedSizeCollection(); return false; } [Inline] internal static void RemoveAt( T[] _this , int index ) { // Not meaningful for arrays ArrayImpl.Throw_FixedSizeCollection(); } // This is a normal generic Enumerator for SZ arrays. It doesn't have any of the "this" voodoo // that SZArrayHelper does. // [Serializable] private sealed class SZGenericArrayEnumerator : System.Collections.Generic.IEnumerator<T> { private T[] m_array; private int m_index; private int m_endIndex; // cache array length, since it's a little slow. internal SZGenericArrayEnumerator( T[] array ) { //// BCLDebug.Assert( array.Rank == 1 && array.GetLowerBound( 0 ) == 0, "SZArrayEnumerator<T> only works on single dimension arrays w/ a lower bound of zero." ); m_array = array; m_index = -1; m_endIndex = array.Length; } public bool MoveNext() { if(m_index < m_endIndex) { m_index++; return (m_index < m_endIndex); } return false; } public T Current { get { //// if(m_index < 0) //// { //// throw new InvalidOperationException( Environment.GetResourceString( ResId.InvalidOperation_EnumNotStarted ) ); //// } //// //// if(m_index >= m_endIndex) //// { //// throw new InvalidOperationException( Environment.GetResourceString( ResId.InvalidOperation_EnumEnded ) ); //// } return m_array[m_index]; } } object System.Collections.IEnumerator.Current { get { return Current; } } void System.Collections.IEnumerator.Reset() { m_index = -1; } public void Dispose() { } } } }
namespace Microsoft.Protocols.TestSuites.Common { using System; using System.Collections.Generic; using Microsoft.Protocols.TestTools; /// <summary> /// This class represents context which will be used to shared necessary information for both the MS-FSSHTTP and MS-WOPI. /// </summary> public class SharedContext { /// <summary> /// Specify the thread local storage context. /// </summary> [ThreadStatic] private static SharedContext current; /// <summary> /// Specify the properties stored in the context. /// </summary> private Dictionary<string, object> properties; /// <summary> /// Prevents a default instance of the SharedContext class from being created. /// </summary> private SharedContext() { this.properties = new Dictionary<string, object>(); } /// <summary> /// Gets the current context stored in the thread local storage. /// </summary> public static SharedContext Current { get { if (current == null) { current = new SharedContext(); } return current; } } /// <summary> /// Gets or sets an object provides logging, assertions, and SUT adapters for test code onto its execution context. /// </summary> public ITestSite Site { get { return this.GetValueOrDefault<ITestSite>("Site"); } set { this.AddOrUpdate("Site", value); } } /// <summary> /// Gets or sets the operation type which will indicate whether the operations are defined in MS-WOPI and MS-FSSHTTP. /// </summary> public OperationType OperationType { get { return this.GetValueOrDefault<OperationType>("OperationType", OperationType.FSSHTTPCellStorageRequest); } set { this.AddOrUpdate("OperationType", value); } } /// <summary> /// Gets or sets the VersionType defined in the MS-FSSHTTP. /// </summary> public VersionType CellStorageVersionType { get { return this.GetValueOrDefault<VersionType>("CellStorageVersionType"); } set { this.AddOrUpdate("CellStorageVersionType", value); } } /// <summary> /// Gets or sets request target Url. /// </summary> public string TargetUrl { get { return this.GetValueOrDefault<string>("TargetUrl"); } set { this.AddOrUpdate("TargetUrl", value); } } public string FileUrl { get { return this.GetValueOrDefault<string>("FileUrl"); } set { this.AddOrUpdate("FileUrl", value); } } /// <summary> /// Gets or sets the endpoint configuration name. /// </summary> public string EndpointConfigurationName { get { return this.GetValueOrDefault<string>("EndpointConfigurationName"); } set { this.AddOrUpdate("EndpointConfigurationName", value); } } /// <summary> /// Gets or sets the user name. /// </summary> public string UserName { get { return this.GetValueOrDefault<string>("UserName"); } set { this.AddOrUpdate("UserName", value); } } /// <summary> /// Gets or sets the password. /// </summary> public string Password { get { return this.GetValueOrDefault<string>("Password"); } set { this.AddOrUpdate("Password", value); } } /// <summary> /// Gets or sets the domain. /// </summary> public string Domain { get { return this.GetValueOrDefault<string>("Domain"); } set { this.AddOrUpdate("Domain", value); } } /// <summary> /// Gets or sets the X-WOPI-ProofOld header value defined in the MS-WOPI. /// </summary> public string XWOPIProofOld { get { return this.GetValueOrDefault<string>("XWOPIProofOld"); } set { this.AddOrUpdate("XWOPIProofOld", value); } } /// <summary> /// Gets or sets the X-WOPI-Proof header value defined in the MS-WOPI. /// </summary> public string XWOPIProof { get { return this.GetValueOrDefault<string>("XWOPIProof"); } set { this.AddOrUpdate("XWOPIProof", value); } } /// <summary> /// Gets or sets the X-WOPI-TimeStamp header value defined in the MS-WOPI. /// </summary> public string XWOPITimeStamp { get { return this.GetValueOrDefault<string>("XWOPITimeStamp"); } set { this.AddOrUpdate("XWOPITimeStamp", value); } } /// <summary> /// Gets or sets the Authorization header value defined in the MS-WOPI. /// </summary> public string XWOPIAuthorization { get { return this.GetValueOrDefault<string>("XWOPIAuthorization"); } set { this.AddOrUpdate("XWOPIAuthorization", value); } } /// <summary> /// Gets or sets the X-WOPI-RelativeTarget header value defined in the MS-WOPI. /// </summary> public string XWOPIRelativeTarget { get { return this.GetValueOrDefault<string>("X-WOPI-RelativeTarget"); } set { this.AddOrUpdate("X-WOPI-RelativeTarget", value); } } /// <summary> /// Gets or sets the X-WOPI-Override header value defined in the MS-WOPI. /// </summary> public string XWOPIOverride { get { return this.GetValueOrDefault<string>("X-WOPI-Override"); } set { this.AddOrUpdate("X-WOPI-Override", value); } } /// <summary> /// Gets or sets the X-WOPI-Size header value defined in the MS-WOPI. /// </summary> public string XWOPISize { get { return this.GetValueOrDefault<string>("X-WOPI-Size"); } set { this.AddOrUpdate("X-WOPI-Size", value); } } /// <summary> /// Gets or sets a value indicating whether the X-WOPI-RelativeTarget header is send. If true, the channel will send optional X-WOPI-RelativeTarget header. Otherwise it will not send. /// The default value is true if it is not set. /// </summary> public bool IsXWOPIRelativeTargetSpecified { get { return this.GetValueOrDefault<bool>("IsXWOPIRelativeTargetSpecified", true); } set { this.AddOrUpdate("IsXWOPIRelativeTargetSpecified", value); } } /// <summary> /// Gets or sets a value indicating whether the X-WOPI-Override header is send. If true, the channel will send optional X-WOPI-Override header. Otherwise it will not send. /// The default value is true if it is not set. /// </summary> public bool IsXWOPIOverrideSpecified { get { return this.GetValueOrDefault<bool>("IsXWOPIOverrideSpecified", true); } set { this.AddOrUpdate("IsXWOPIOverrideSpecified", value); } } /// <summary> /// Gets or sets a value indicating whether the X-WOPI-Size header is send. If true, the channel will send optional X-WOPI-Size header. Otherwise it will not send. /// The default value is true if it is not set. /// </summary> public bool IsXWOPISizeSpecified { get { return this.GetValueOrDefault<bool>("IsXWOPISizeSpecified", true); } set { this.AddOrUpdate("IsXWOPISizeSpecified", value); } } /// <summary> /// Gets or sets a value indicating whether MS-FSSHTTP related requirements will be captured. If the OperationType is FSSHTTPCellStorageRequest <see cref="TestSuites.Common.OperationType"/>, it will always return true. /// Otherwise, the default value is false if it is not set. /// </summary> public bool IsMsFsshttpRequirementsCaptured { get { if (this.OperationType == TestSuites.Common.OperationType.FSSHTTPCellStorageRequest) { return true; } return this.GetValueOrDefault<bool>("IsMsFsshttpRequirementsCaptured", false); } set { this.AddOrUpdate("IsMsFsshttpRequirementsCaptured", value); } } /// <summary> /// This method is used to get the value with the specified key if it exists. /// If the key does not exist, the default(T) value will be returned. /// </summary> /// <typeparam name="T">Specify the type of the value.</typeparam> /// <param name="key">Specify the key.</param> /// <returns>Return the value associated with the key.</returns> public T GetValueOrDefault<T>(string key) { return this.GetValueOrDefault<T>(key, default(T)); } /// <summary> /// This method is used to get the value with the specified key if it exists. /// If the key does not exist, the defaultValue value will be returned. /// </summary> /// <typeparam name="T">Specify the type of the value.</typeparam> /// <param name="key">Specify the key.</param> /// <param name="defaultValue">Specify the default value.</param> /// <returns>Return the value associated with the key.</returns> public T GetValueOrDefault<T>(string key, T defaultValue) { object outValue; if (!this.properties.TryGetValue(key, out outValue)) { return defaultValue; } return (T)outValue; } /// <summary> /// This method is used to create or update the entry with the specified key. /// </summary> /// <param name="key">Specify the key.</param> /// <param name="value">Specify the value.</param> public void AddOrUpdate(string key, object value) { if (!this.properties.ContainsKey(key)) { this.properties.Add(key, value); } else { this.properties[key] = value; } } /// <summary> /// Clear all the current context properties. /// </summary> public void Clear() { this.properties.Clear(); } } }
// Copyright (C) 2015 The Apterid Developers - See LICENSE using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading; using System.Threading.Tasks; using Apterid.Bootstrap.Common; using Apterid.Bootstrap.Parse; using Verophyle.CSLogic; namespace Apterid.Bootstrap.Analyze { public class ApteridAnalyzer { public Context Context { get; } public AnalysisUnit Unit { get; private set; } public ParsedSourceFile SourceFile { get; } public ApteridAnalyzer(Context context, ParsedSourceFile sourceFile, AnalysisUnit analyzeUnit) { Context = context; Unit = analyzeUnit; SourceFile = sourceFile; } public void Analyze(CancellationToken cancel) { var sourceNode = SourceFile.ParseTree as Parse.Syntax.Source; if (sourceNode == null) { Unit.AddError(new AnalyzerError { ErrorNode = SourceFile.ParseTree, Message = string.Format(ErrorMessages.E_0010_Analyzer_ParseTreeIsNotSource, SourceFile.Name) }); return; } var modules = AnalyzeSource(sourceNode, cancel).Result; if (Unit.Errors.Any() && Context.AbortOnError) return; ResolveTypes(modules, cancel); } #region Semantic Analysis Task<Module[]> AnalyzeSource(Parse.Syntax.Source sourceNode, CancellationToken cancel) { var nodesAndModules = new List<Tuple<Parse.Syntax.Module, Module>>(); // collect top-level modules var triviaNodes = new List<Parse.Syntax.Node>(); Module curModule = null; Parse.Syntax.Module moduleNode = null; foreach (var node in sourceNode.Children) { if (cancel.IsCancellationRequested) throw new OperationCanceledException(cancel); if ((moduleNode = node as Parse.Syntax.Module) != null) { // look for existing module var moduleName = new QualifiedName { Qualifiers = moduleNode.Qualifiers.Select(id => id.Text), Name = moduleNode.Name.Text }; lock (Unit.Modules) { if (!Unit.Modules.TryGetValue(moduleName, out curModule)) { curModule = new Module { Name = moduleName }; Unit.Modules.Add(curModule.Name, curModule); } foreach (var tn in triviaNodes) curModule.PreTrivia.Add(tn); triviaNodes.Clear(); } nodesAndModules.Add(Tuple.Create(moduleNode, curModule)); } else if (node is Parse.Syntax.Directive) { throw new NotImplementedException(); } else if (node is Parse.Syntax.Space) { triviaNodes.Add(node); } else { Unit.AddError(new AnalyzerError { ErrorNode = node, Message = string.Format(ErrorMessages.E_0011_Analyzer_InvalidToplevelItem, ApteridError.Truncate(node.Text)), }); } } if (curModule != null) { foreach (var tn in triviaNodes) curModule.PostTrivia.Add(tn); } // analyze var tasks = nodesAndModules.Select(mm => AnalyzeModule(mm.Item1, mm.Item2, cancel)); return Task.WhenAll(tasks); } Task<Module> AnalyzeModule(Parse.Syntax.Module moduleNode, Module module, CancellationToken cancel) { var bindings = new List<Tuple<Parse.Syntax.Binding, Binding>>(); // collect module bindings var triviaNodes = new List<Parse.Syntax.Node>(); Binding curBinding = null; Parse.Syntax.Binding bindingNode = null; foreach (var node in moduleNode.Body) { if (cancel.IsCancellationRequested) throw new OperationCanceledException(cancel); if ((bindingNode = node as Parse.Syntax.Binding) != null) { var bindingName = new QualifiedName(module, bindingNode.Name.Text); lock (module.Bindings) { if (module.Bindings.TryGetValue(bindingName, out curBinding)) { Unit.AddError(new AnalyzerError { ErrorNode = node, Message = string.Format(ErrorMessages.E_0012_Analyzer_DuplicateBinding, bindingName.Name), }); } else { curBinding = new Binding { Parent = module, Name = bindingName, SyntaxNode = bindingNode }; bindings.Add(Tuple.Create(bindingNode, curBinding)); module.Bindings.Add(curBinding.Name, curBinding); } foreach (var tn in triviaNodes) curBinding.PreTrivia.Add(tn); triviaNodes.Clear(); } } else if (node is Parse.Syntax.Space) { triviaNodes.Add(node); } else { Unit.AddError(new AnalyzerError { ErrorNode = node, Message = string.Format(ErrorMessages.E_0013_Analyzer_InvalidScopeItem, ApteridError.Truncate(node.Text)), }); } } if (curBinding != null) { foreach (var tn in triviaNodes) curBinding.PostTrivia.Add(tn); } // analyze var tasks = bindings.Select(bb => Task.Factory.StartNew(() => AnalyzeBinding(module, bb.Item1, bb.Item2, cancel), TaskCreationOptions.AttachedToParent)); return Task.WhenAll(tasks).ContinueWith(t => module); } void AnalyzeBinding(Module module, Parse.Syntax.Binding bindingNode, Binding binding, CancellationToken cancel) { if (bindingNode.Body == null || !bindingNode.Body.Any()) { Unit.AddError(new AnalyzerError { ErrorNode = bindingNode, Message = string.Format(ErrorMessages.E_0014_Analyzer_EmptyBinding, bindingNode.Name.Text), }); return; } var triviaNodes = new List<Parse.Syntax.Node>(); Expression expression = null; Parse.Syntax.Literal literalNode; Parse.Syntax.Literal<BigInteger> bigIntLiteral; foreach (var node in bindingNode.Body) { if (cancel.IsCancellationRequested) throw new OperationCanceledException(cancel); if ((literalNode = node as Parse.Syntax.Literal) != null) { if ((bigIntLiteral = literalNode as Parse.Syntax.Literal<BigInteger>) != null) { expression = new Expressions.IntegerLiteral(bigIntLiteral.Value) { SyntaxNode = bigIntLiteral }; } else { throw new NotImplementedException(string.Format("Literals of type {0} not implemented yet.", literalNode.ValueType.Name)); } } else if (node is Parse.Syntax.Space) { triviaNodes.Add(node); } } if (expression == null) { Unit.AddError(new AnalyzerError { ErrorNode = bindingNode, Message = string.Format(ErrorMessages.E_0014_Analyzer_EmptyBinding, bindingNode.Name.Text), }); return; } foreach (var tn in triviaNodes) expression.PostTrivia.Add(tn); binding.Expression = expression; } #endregion #region Type Resolution struct TypeResolveRec { public Goal<Type> Constraint { get; set; } public IEnumerable<Tuple<Expression, Var>> ExpTypeVars { get; set; } } void ResolveTypes(IEnumerable<Module> modules, CancellationToken cancel) { var trr = new TypeResolveRec { Constraint = s => new[] { s }, // true ExpTypeVars = Enumerable.Empty<Tuple<Expression, Var>>(), }; trr = modules.Aggregate(trr, (mtr, m) => { if (cancel.IsCancellationRequested) throw new OperationCanceledException(cancel); return m.Bindings.Values.Aggregate(mtr, (btr, b) => { if (cancel.IsCancellationRequested) throw new OperationCanceledException(cancel); return ResolveExpressionType(btr, b.Expression); }); }); try { var varTypes = Goal.Eval(trr.Constraint).First(); foreach (var expVar in trr.ExpTypeVars) { var e = expVar.Item1; var v = expVar.Item2; if (varTypes.Binds(v)) { e.ResolvedType = varTypes[v]; } else { Unit.AddError(new AnalyzerError { ErrorNode = e.SyntaxNode, Message = string.Format(ErrorMessages.E_0015_Analyzer_UnableToInferType, ApteridError.Truncate(e.SyntaxNode.Text)), }); } } } catch (OperationCanceledException) { throw; } catch (Exception e) { Unit.AddError(new AnalyzerError { Exception = e }); } } TypeResolveRec ResolveExpressionType(TypeResolveRec tvr, Expression e) { tvr = e.Children.Aggregate(tvr, (tvrc, c) => ResolveExpressionType(tvrc, c)); var v = Var.NewVar(); var result = new TypeResolveRec { Constraint = Goal.Conj(tvr.Constraint, e.ResolveType(v)), ExpTypeVars = tvr.ExpTypeVars.Concat(new[] { Tuple.Create(e, v) }), }; return result; } #endregion } public class AnalyzerError : NodeError { } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using VelcroPhysics.Collision.Shapes; using VelcroPhysics.Dynamics; using VelcroPhysics.Extensions.Controllers.ControllerBase; using VelcroPhysics.Shared; using VelcroPhysics.Utilities; namespace VelcroPhysics.Extensions.Controllers.Buoyancy { public sealed class BuoyancyController : Controller { private AABB _container; private Vector2 _gravity; private Vector2 _normal; private float _offset; private Dictionary<int, Body> _uniqueBodies = new Dictionary<int, Body>(); /// <summary> /// Controls the rotational drag that the fluid exerts on the bodies within it. Use higher values will simulate thick /// fluid, like honey, lower values to /// simulate water-like fluids. /// </summary> public float AngularDragCoefficient; /// <summary> /// Density of the fluid. Higher values will make things more buoyant, lower values will cause things to sink. /// </summary> public float Density; /// <summary> /// Controls the linear drag that the fluid exerts on the bodies within it. Use higher values will simulate thick fluid, /// like honey, lower values to /// simulate water-like fluids. /// </summary> public float LinearDragCoefficient; /// <summary> /// Acts like waterflow. Defaults to 0,0. /// </summary> public Vector2 Velocity; /// <summary> /// Initializes a new instance of the <see cref="BuoyancyController" /> class. /// </summary> /// <param name="container">Only bodies inside this AABB will be influenced by the controller</param> /// <param name="density">Density of the fluid</param> /// <param name="linearDragCoefficient">Linear drag coefficient of the fluid</param> /// <param name="rotationalDragCoefficient">Rotational drag coefficient of the fluid</param> /// <param name="gravity">The direction gravity acts. Buoyancy force will act in opposite direction of gravity.</param> public BuoyancyController(AABB container, float density, float linearDragCoefficient, float rotationalDragCoefficient, Vector2 gravity) : base(ControllerType.BuoyancyController) { Container = container; _normal = new Vector2(0, 1); Density = density; LinearDragCoefficient = linearDragCoefficient; AngularDragCoefficient = rotationalDragCoefficient; _gravity = gravity; } public AABB Container { get { return _container; } set { _container = value; _offset = _container.UpperBound.Y; } } public override void Update(float dt) { _uniqueBodies.Clear(); World.QueryAABB(fixture => { if (fixture.Body.IsStatic || !fixture.Body.Awake) return true; if (!_uniqueBodies.ContainsKey(fixture.Body.BodyId)) _uniqueBodies.Add(fixture.Body.BodyId, fixture.Body); return true; }, ref _container); foreach (KeyValuePair<int, Body> kv in _uniqueBodies) { Body body = kv.Value; Vector2 areac = Vector2.Zero; Vector2 massc = Vector2.Zero; float area = 0; float mass = 0; for (int j = 0; j < body.FixtureList.Count; j++) { Fixture fixture = body.FixtureList[j]; if (fixture.Shape.ShapeType != ShapeType.Polygon && fixture.Shape.ShapeType != ShapeType.Circle) continue; Shape shape = fixture.Shape; Vector2 sc; float sarea = ComputeSubmergedArea(shape, ref _normal, _offset, ref body._xf, out sc); area += sarea; areac.X += sarea * sc.X; areac.Y += sarea * sc.Y; mass += sarea * shape.Density; massc.X += sarea * sc.X * shape.Density; massc.Y += sarea * sc.Y * shape.Density; } areac.X /= area; areac.Y /= area; massc.X /= mass; massc.Y /= mass; if (area < Settings.Epsilon) continue; //Buoyancy Vector2 buoyancyForce = -Density * area * _gravity; body.ApplyForce(buoyancyForce, massc); //Linear drag Vector2 dragForce = body.GetLinearVelocityFromWorldPoint(areac) - Velocity; dragForce *= -LinearDragCoefficient * area; body.ApplyForce(dragForce, areac); //Angular drag body.ApplyTorque(-body.Inertia / body.Mass * area * body.AngularVelocity * AngularDragCoefficient); } } private float ComputeSubmergedArea(Shape shape, ref Vector2 normal, float offset, ref Transform xf, out Vector2 sc) { switch (shape.ShapeType) { case ShapeType.Circle: { CircleShape circleShape = (CircleShape)shape; sc = Vector2.Zero; Vector2 p = MathUtils.Mul(ref xf, circleShape.Position); float l = -(Vector2.Dot(normal, p) - offset); if (l < -circleShape.Radius + Settings.Epsilon) { //Completely dry return 0; } if (l > circleShape.Radius) { //Completely wet sc = p; return Settings.Pi * circleShape._2radius; } //Magic float l2 = l * l; float area = circleShape._2radius * (float)((Math.Asin(l / circleShape.Radius) + Settings.Pi / 2) + l * Math.Sqrt(circleShape._2radius - l2)); float com = -2.0f / 3.0f * (float)Math.Pow(circleShape._2radius - l2, 1.5f) / area; sc.X = p.X + normal.X * com; sc.Y = p.Y + normal.Y * com; return area; } case ShapeType.Edge: sc = Vector2.Zero; return 0; case ShapeType.Polygon: { sc = Vector2.Zero; PolygonShape polygonShape = (PolygonShape)shape; //Transform plane into shape co-ordinates Vector2 normalL = MathUtils.MulT(xf.q, normal); float offsetL = offset - Vector2.Dot(normal, xf.p); float[] depths = new float[Settings.MaxPolygonVertices]; int diveCount = 0; int intoIndex = -1; int outoIndex = -1; bool lastSubmerged = false; int i; for (i = 0; i < polygonShape.Vertices.Count; i++) { depths[i] = Vector2.Dot(normalL, polygonShape.Vertices[i]) - offsetL; bool isSubmerged = depths[i] < -Settings.Epsilon; if (i > 0) { if (isSubmerged) { if (!lastSubmerged) { intoIndex = i - 1; diveCount++; } } else { if (lastSubmerged) { outoIndex = i - 1; diveCount++; } } } lastSubmerged = isSubmerged; } switch (diveCount) { case 0: if (lastSubmerged) { //Completely submerged sc = MathUtils.Mul(ref xf, polygonShape.MassData.Centroid); return polygonShape.MassData.Mass / Density; } //Completely dry return 0; case 1: if (intoIndex == -1) { intoIndex = polygonShape.Vertices.Count - 1; } else { outoIndex = polygonShape.Vertices.Count - 1; } break; } int intoIndex2 = (intoIndex + 1) % polygonShape.Vertices.Count; int outoIndex2 = (outoIndex + 1) % polygonShape.Vertices.Count; float intoLambda = (0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex]); float outoLambda = (0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex]); Vector2 intoVec = new Vector2(polygonShape.Vertices[intoIndex].X * (1 - intoLambda) + polygonShape.Vertices[intoIndex2].X * intoLambda, polygonShape.Vertices[intoIndex].Y * (1 - intoLambda) + polygonShape.Vertices[intoIndex2].Y * intoLambda); Vector2 outoVec = new Vector2(polygonShape.Vertices[outoIndex].X * (1 - outoLambda) + polygonShape.Vertices[outoIndex2].X * outoLambda, polygonShape.Vertices[outoIndex].Y * (1 - outoLambda) + polygonShape.Vertices[outoIndex2].Y * outoLambda); //Initialize accumulator float area = 0; Vector2 center = new Vector2(0, 0); Vector2 p2 = polygonShape.Vertices[intoIndex2]; const float k_inv3 = 1.0f / 3.0f; //An awkward loop from intoIndex2+1 to outIndex2 i = intoIndex2; while (i != outoIndex2) { i = (i + 1) % polygonShape.Vertices.Count; Vector2 p3; if (i == outoIndex2) p3 = outoVec; else p3 = polygonShape.Vertices[i]; //Add the triangle formed by intoVec,p2,p3 { Vector2 e1 = p2 - intoVec; Vector2 e2 = p3 - intoVec; float D = MathUtils.Cross(e1, e2); float triangleArea = 0.5f * D; area += triangleArea; // Area weighted centroid center += triangleArea * k_inv3 * (intoVec + p2 + p3); } p2 = p3; } //Normalize and transform centroid center *= 1.0f / area; sc = MathUtils.Mul(ref xf, center); return area; } case ShapeType.Chain: sc = Vector2.Zero; return 0; case ShapeType.Unknown: case ShapeType.TypeCount: throw new NotSupportedException(); default: throw new ArgumentOutOfRangeException(); } } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Reflection; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OSD = OpenMetaverse.StructuredData.OSD; using Caps = OpenSim.Framework.Communications.Capabilities.Caps; namespace OpenSim.Region.CoreModules.Capabilities { /// <summary> /// SimulatorFeatures capability. /// </summary> /// <remarks> /// This is required for uploading Mesh. /// Since is accepts an open-ended response, we also send more information /// for viewers that care to interpret it. /// /// NOTE: Part of this code was adapted from the Aurora project, specifically /// the normal part of the response in the capability handler. /// </remarks> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class SimulatorFeaturesModule : ISharedRegionModule, ISimulatorFeaturesModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; /// <summary> /// Simulator features /// </summary> private OSDMap m_features = new OSDMap(); private string m_MapImageServerURL = String.Empty; private string m_SearchURL = String.Empty; private bool m_MeshEnabled = true; private bool m_PhysicsMaterialsEnabled = true; private float m_RenderMaterialsCapability = 1.0f; private int m_MaxMaterialsPerTransaction = 50; private bool m_DynamicPathfindingEnabled = false; private bool m_ExportSupported = true; private int m_whisperdistance = 10; private int m_saydistance = 30; private int m_shoutdistance = 100; #region ISharedRegionModule Members public void Initialize(IConfigSource source) { IConfig config = source.Configs["SimulatorFeatures"]; if (config != null) { m_MapImageServerURL = config.GetString("MapImageServerURI", String.Empty); if (!String.IsNullOrEmpty(m_MapImageServerURL)) { m_MapImageServerURL = m_MapImageServerURL.Trim(); if (!m_MapImageServerURL.EndsWith("/")) m_MapImageServerURL = m_MapImageServerURL + "/"; } m_SearchURL = config.GetString("SearchServerURI", String.Empty); m_MeshEnabled = config.GetBoolean("MeshEnabled", m_MeshEnabled); m_PhysicsMaterialsEnabled = config.GetBoolean("PhysicsMaterialsEnabled", m_MeshEnabled); m_RenderMaterialsCapability = config.GetFloat("RenderMaterialsCapability", m_RenderMaterialsCapability); m_MaxMaterialsPerTransaction = config.GetInt("MaxMaterialsPerTransaction", m_MaxMaterialsPerTransaction); m_DynamicPathfindingEnabled = config.GetBoolean("DynamicPathfindingEnabled", m_DynamicPathfindingEnabled); m_ExportSupported = config.GetBoolean("ExportSupported", m_ExportSupported); } // Now the chat params to be returned by the SimulatorFeatures response config = source.Configs["Chat"]; if (config != null) { m_whisperdistance = config.GetInt("whisper_distance", m_whisperdistance); m_saydistance = config.GetInt("say_distance", m_saydistance); m_shoutdistance = config.GetInt("shout_distance", m_shoutdistance); } AddDefaultFeatures(); } public void AddRegion(Scene s) { m_scene = s; m_scene.RegisterModuleInterface<ISimulatorFeaturesModule>(this); m_scene.EventManager.OnRegisterCaps += RegisterCaps; } public void RemoveRegion(Scene s) { m_scene.EventManager.OnRegisterCaps -= RegisterCaps; } public void RegionLoaded(Scene s) { } public void PostInitialize() { } public void Close() { } public string Name { get { return "SimulatorFeaturesModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion /// <summary> /// Add default features /// </summary> /// <remarks> /// TODO: These should be added from other modules rather than hardcoded. /// </remarks> private void AddDefaultFeatures() { lock (m_features) { m_features["MeshRezEnabled"] = m_MeshEnabled; m_features["MeshUploadEnabled"] = m_MeshEnabled; m_features["MeshXferEnabled"] = m_MeshEnabled; m_features["PhysicsMaterialsEnabled"] = m_PhysicsMaterialsEnabled; m_features["RenderMaterialsCapability"] = m_RenderMaterialsCapability; m_features["MaxMaterialsPerTransaction"] = m_MaxMaterialsPerTransaction; m_features["DynamicPathfindingEnabled"] = m_DynamicPathfindingEnabled; m_features["AvatarHoverHeightEnabled"] = true; OSDMap typesMap = new OSDMap(); typesMap["convex"] = true; typesMap["none"] = true; typesMap["prim"] = true; m_features["PhysicsShapeTypes"] = typesMap; // Extra information for viewers that want to use it OSDMap opensimFeatures = new OSDMap(); if (!String.IsNullOrEmpty(m_MapImageServerURL)) opensimFeatures["map-server-url"] = OSD.FromString(m_MapImageServerURL); if (!String.IsNullOrEmpty(m_SearchURL)) opensimFeatures["search-server-url"] = OSD.FromString(m_SearchURL); opensimFeatures["ExportSupported"] = m_ExportSupported; opensimFeatures["whisper-range"] = m_whisperdistance; opensimFeatures["say-range"] = m_saydistance; opensimFeatures["shout-range"] = m_shoutdistance; m_features["OpenSimExtras"] = opensimFeatures; m_log.InfoFormat("[SimulatorFeatures]: mesh={0} physMat={1} exp={2} map='{3}' search='{4}'", m_MeshEnabled, m_PhysicsMaterialsEnabled, m_ExportSupported, m_MapImageServerURL, m_SearchURL); } } public void RegisterCaps(UUID agentID, Caps caps) { IRequestHandler reqHandler = new RestHTTPHandler("GET", "/CAPS/" + UUID.Random(), HandleSimulatorFeaturesRequest); caps.RegisterHandler("SimulatorFeatures", reqHandler); } public bool MeshEnabled { get { return m_MeshEnabled; } } public bool PhysicsMaterialsEnabled { get { return m_PhysicsMaterialsEnabled; } } public void AddFeature(string name, OSD value) { lock (m_features) m_features[name] = value; } public bool RemoveFeature(string name) { lock (m_features) return m_features.Remove(name); } public bool TryGetFeature(string name, out OSD value) { lock (m_features) return m_features.TryGetValue(name, out value); } public OSDMap GetFeatures() { lock (m_features) return new OSDMap(m_features); } private Hashtable HandleSimulatorFeaturesRequest(Hashtable mDhttpMethod) { // m_log.DebugFormat("[SIMULATOR FEATURES MODULE]: SimulatorFeatures request"); //Send back data Hashtable responsedata = new Hashtable(); responsedata["int_response_code"] = 200; responsedata["content_type"] = "text/plain"; lock (m_features) responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(m_features); return responsedata; } } }
using UnityEngine; using System.Collections; using JumpAndRun; public class GameControllerScript : MonoBehaviour { //flaby_alien_level_two private static RuntimePlatform platform; public bool isMobilePlatform = false; private static GameControllerScript instance; //number of energy star pickups spread in level public int numberEnergyPickups = 20; public Texture2D pauseIcon; public Texture2D playIcon; public Texture2D backButton; public Texture2D forwardButton; public Texture2D JumpButton; private Texture2D rateTexture; private Texture2D exitTexture; public int screenWidth; public int screenHeight; Rect pausePlayRect; Rect exitTextureRect; Rect leaderboardsRect; Rect rateRect; Rect forwardRect; Rect backRect; Rect jumpRect; public bool isGamePaused = true; private bool isGameStarted = false; private bool isGameOver = true; private bool isGameComplete = false; private GUITexture redTexture; //public bool isRestart = false; public Font messagesFont; public int messagesFontSizeSmaller; public int messagesFontSizeLarger; //when hurry up, increase scrolling speed of platforms by 1.8 const float HURRY_UP_SPEED_INCREASE_FACTOR = 1.8f; //whne to hurry up 1/4 of total mission seconds const float HURRY_UP_START_FACTOR = 0.25f; private bool appliedHurryUpFactor = false; private string hurryUpMessage = "Hurry Up!"; private float initialHurryUpMessageTime = 0f; private bool isShowingHurryUpMessage = false; private bool hasMovedSpikesLine = false; //controll first level howTo private float lastHowToTime = 0f; private float initialHowToTime = 0f; private bool isShowingHowTo = false; private GUISkin skin; public int numWorlds = 4; public int numberOfLevels = 10; public int currentLevel = 1; public int currentWorld = 1; //number of minutes to complete the mission //display time private int elapsedMissionSeconds = 0; //show in app for level xxx? private bool showUnlockLevel = true; //Iads only // private ADBannerView banner = null; //#if UNITY_IPHONE //private ADBannerView banner; //#endif private int currentTime = 0; //ads stuff //private BannerView bannerView; public bool isRollingFinalCredits = false; PlayerScript player; GameObject motherShip; bool buyedPremium; bool buyedNoads; private bool openedPlatform = false; GUIResolutionHelper resolutionHelper; private TextLocalizationManager translationManager; private int highScore = 0; Texture2D leaderBoardTexture; //private SocialAPI socialAPIInstance; private bool buyedExtraLifes = false; private bool buyedExtraTime = false; private bool buyedExtraSpeed = false; private bool buyedInfiniteLifes = false; private GameObject[] paralaxLevels; void Awake() { //DontDestroyOnLoad(this); if(instance!=null) { Debug.Log("There is another instance gamecontroller running"); } else { instance = this; } //check screen size, this was breaking, probably some place we are calling Instance GameObject scripts = GameObject.FindGameObjectWithTag("Scripts"); if(scripts!=null) { resolutionHelper = scripts.GetComponent<GUIResolutionHelper>(); translationManager = scripts.GetComponent<TextLocalizationManager>(); } else { resolutionHelper = GUIResolutionHelper.Instance; //handle translation language translationManager = TextLocalizationManager.Instance; } screenWidth = resolutionHelper.screenWidth; screenHeight = resolutionHelper.screenHeight; //translations translationManager.LoadSystemLanguage(Application.systemLanguage); InitPlayer(); //get a reference to the object //socialAPIInstance = SocialAPI.Instance; //set the score key pref, if not set yet openedPlatform = false; showUnlockLevel = false; isGameOver = true; isGameStarted = false; //this was true before isGamePaused = true; isRollingFinalCredits = false; //we need to do this before we do the time math, so we can update in case of an existing in app purchase CheckInAppPurchases(); //seconds to display elapsedMissionSeconds = 0; CheckPause(); lastHowToTime = 0f; initialHowToTime = 0f; isShowingHowTo = false; } // Use this for initialization void Start () { skin = Resources.Load("GUISkin") as GUISkin; exitTexture = Resources.Load("button_playstart") as Texture2D; rateTexture = Resources.Load("button_rate") as Texture2D; // exitTexture = Resources.Load("button_playstart") as Texture2D; isGameComplete = false; //?? appliedHurryUpFactor = false; hasMovedSpikesLine = false; isGameOver = true; if(isGameOver && currentWorld==1 && currentLevel==1) { initialHowToTime = Time.realtimeSinceStartup; lastHowToTime = initialHowToTime; } paralaxLevels = GameObject.FindGameObjectsWithTag("Scroller"); } /** * Check if we have bought any boosters */ void CheckInAppPurchases() { } IEnumerator Fade (float start,float end, float length) { Color aux = redTexture.color; //define Fade parmeters if (aux.a == start){ for (float i = 0.0f; i < 1.0f; i += Time.deltaTime*(1/length)) { //for the length of time aux.a = Mathf.Lerp(start, end, i); //lerp the value of the transparency from the start value to the end value in equal increments yield return null; aux.a = end; // ensure the fade is completely finished (because lerp doesn't always end on an exact value) redTexture.color = aux; } //end for } //end if } //end Fade /* The above example (in FlashWhenHit) will fade your texture from 100% transparent (invisible) to 80% opaque (just slightly transparent) over 1/2 second. It checks to make sure the texture is 100% transparent before attempting the fade to eliminate visual errors, and at the end ensures it is at exactly 80% opacity. It will then wait 1/100th second, and fade the texture back out to transparent. You can, of course, adjust the starting and ending opacity by changing the start and end values in the function call, as well as how long the fade takes and what object if affects. The WaitForSeconds is in there so the texture will stay at its max opacity momentarily (to make it more visually obvious); the length of time is adjustable there too. Also, if you want the screen to flash a certain number of times, you could use a for loop with a counter that goes to 0 from, say, 3, to get the screen to flash 3 times, etc. */ void FlashWhenInHurryUpMessage (){ StartCoroutine(Fade (0f, 0.1f, 0.5f)); StartCoroutine(MyWaitMethod()); StartCoroutine(Fade (0.1f, 0f, 0.5f)); } IEnumerator MyWaitMethod() { yield return new WaitForSeconds(.01f); } //setup player stuff void InitPlayer() { GameObject obj = GameObject.FindGameObjectWithTag("Player"); if(obj!=null) { player = obj.GetComponent<PlayerScript>(); } } //invoked every second void CheckMissionTime() { if(!isGamePaused && player!=null && player.IsPlayerAlive()) { elapsedMissionSeconds+=1; }//if !gamePaused } /** * Add extra seconds */ public void IncreaseTimeSecondsBy(int seconds) { //do we overlap the min? elapsedMissionSeconds+=seconds; } public int GetCurrentLevel() { return currentLevel; } public int GetCurrentWorld() { return currentWorld; } public void SetCurrentLevel(int level) { currentLevel = level; } public int GetNumberOfLevels() { return numberOfLevels; } public static GameControllerScript Instance { get { if (instance == null) { GameObject scripts = GameObject.FindGameObjectWithTag("Scripts"); if(scripts!=null) { instance = scripts.GetComponentInChildren<GameControllerScript>(); } else { instance = (GameControllerScript)FindObjectOfType(typeof(GameControllerScript)); if (instance == null) instance = (new GameObject("GameControllerScript")).AddComponent<GameControllerScript>(); } } return instance; } } public bool IsGameStarted() { return isGameStarted; } public bool IsShowUnlockNextLevel() { return showUnlockLevel; } //######### music handling ################ public void StartMusic() { AudioSource source = GetGameMusic(); if(source!=null) { source.Play(); } } public void PauseMusic() { AudioSource source = GetGameMusic(); if(source!=null) { source.mute = true; } } public void ResumeMusic() { AudioSource source = GetGameMusic(); if(source!=null) { source.mute = false; } } public void StopMusic() { AudioSource source = GetGameMusic(); if(source!=null) { source.Stop(); } foreach(AudioSource sourceAudio in GetGameAudios()) { if(sourceAudio.isPlaying) { sourceAudio.Stop(); } } } private AudioSource[] GetGameAudios() { AudioSource []audios = FindObjectsOfType<AudioSource>() as AudioSource[]; return audios; } private AudioSource GetGameMusic() { GameObject music = GameObject.FindGameObjectWithTag("GameMusic"); if(music!=null) { AudioSource source = music.GetComponentInChildren<AudioSource>(); return source; } return null; } //############################ void FixedUpdate() { } // Update is called once per frame void Update () { if(isGameStarted && player!=null && player.IsPlayerAlive() && !isGameComplete) { } } private void SpeedUpForegroundPlatforms() { GameObject foreground = GameObject.FindGameObjectWithTag("Foreground"); if(foreground!=null) { ScrollingScript script = foreground.GetComponent<ScrollingScript>(); if(script!=null && script.enabled) { script.speed.x = script.speed.x * HURRY_UP_SPEED_INCREASE_FACTOR; appliedHurryUpFactor = true; } } //also speedup any speedable object SpeedUpSpeedables(); } private void SpeedUpSpeedables() { GameObject [] allSpeedables = GameObject.FindGameObjectsWithTag("SpeedableRotator"); foreach(GameObject speedable in allSpeedables) { Rotator script = speedable.GetComponent<Rotator>(); if(script!=null && script.enabled) { script.rotateSpeed = script.rotateSpeed * HURRY_UP_SPEED_INCREASE_FACTOR; } } } //invoked when final boss is destroyed public void CompletedGame() { isGameComplete = true; //disable camera follow ShowNextScreen(); } private void ShowNextScreen() { bool showNext = (currentLevel < numberOfLevels || currentWorld < numWorlds); EndGame(showNext); //either we died or reached last level, guru time! if(!showNext) { //PerformFinalComputation(true); } else { if(currentLevel < numberOfLevels) { //just increase the level on the same world currentLevel+=1; } else { //save the mission, completed the world /* switch(currentWorld) { case 1: PlayerPrefs.SetInt(GameConstants.MISSION_1_KEY,1); break; case 2: PlayerPrefs.SetInt(GameConstants.MISSION_2_KEY,1); break; case 3: PlayerPrefs.SetInt(GameConstants.MISSION_3_KEY,1); break; case 4: PlayerPrefs.SetInt(GameConstants.MISSION_4_KEY,1); break; }*/ //increase world, set first level currentWorld+=1; currentLevel=1; } //these values keep the next in line //PlayerPrefs.SetInt(GameConstants.PLAYING_WORLD,currentWorld); //PlayerPrefs.SetInt(GameConstants.PLAYING_LEVEL,currentLevel); //PerformFinalComputation(false); //show board and do the math :-) //Application.LoadLevel("NextLevelScene"); } } /** *performs some level calculations and report any achiviement reached */ void PerformFinalComputation(bool finishedGame) { } /** * Check the achievements checkpoints */ void CheckIfReachedAnyAchievementCheckpoint(int totalSaved) { //saved more than 100 already? /*if(totalSaved >= GameConstants.ACHIEVEMENT_BRAVE_CHECKPOINT) { //write the achievement PlayerPrefs.SetInt(GameConstants.ACHIEVEMENT_BRAVE_KEY,1); socialAPIInstance.AddAchievement(GameConstants.ACHIEVEMENT_BRAVE_KEY,100f); } //saved more than 150 already? else if(totalSaved >= GameConstants.ACHIEVEMENT_HERO_CHECKPOINT) { //write the achievement PlayerPrefs.SetInt(GameConstants.ACHIEVEMENT_HERO_KEY,1); socialAPIInstance.AddAchievement(GameConstants.ACHIEVEMENT_HERO_KEY,100f); } //saved more than 100 already? else if(totalSaved >= GameConstants.ACHIEVEMENT_LEGEND_CHECKPOINT) { //write the achievement PlayerPrefs.SetInt(GameConstants.ACHIEVEMENT_LEGEND_KEY,1); socialAPIInstance.AddAchievement(GameConstants.ACHIEVEMENT_LEGEND_KEY,100f); }*/ } /** * Are we on the last level?? */ public bool IsFinalLevel() { return currentWorld==numWorlds && currentLevel==numberOfLevels; } private IEnumerator Wait(long seconds) { yield return new WaitForSeconds(seconds); } public bool IsGameOver() { return isGameOver; } //check if we are on the last level //this is important because the mothership //will have different behaviours public bool IsLastLevel() { return currentLevel == numberOfLevels; } void CheckPause() { Time.timeScale = isGamePaused ? 0f : 1.0f; } public void PauseGame() { /*ScreenShotScript screenshot = GetComponent<ScreenShotScript>(); if(screenshot!=null) { screenshot.EnableScreenshots(); }*/ isGamePaused = true; CheckPause(); PauseMusic(); } public void ResumeGame() { /*ScreenShotScript screenshot = GetComponent<ScreenShotScript>(); if(screenshot!=null) { screenshot.DisableScreenshots(); }*/ isGameOver = false; isGamePaused = false; isGameStarted = true; showUnlockLevel = false; CheckPause(); ResumeMusic(); } public void StartGame() { isGamePaused = false; isGameStarted = true; isGameOver = false; showUnlockLevel = false; /*ScreenShotScript screenshot = GetComponent<ScreenShotScript>(); if(screenshot!=null) { screenshot.DisableScreenshots(); }*/ CheckPause(); StartMusic(); if(currentLevel==1) { //if we are on level 1, clear the history //ClearPlayerPrefs(); //stop invoking the increase function if(currentWorld==1) { //CancelInvoke("IncreaseTimeForHowToTexture"); } } InvokeRepeating("CheckMissionTime", 1.0f, 1.0f); } //i shoul stop the scroll of the level public void EndGame(bool showUnlockNextLevel) { isGameStarted = false; isGameOver = true; isGamePaused = false; StopMusic(); showUnlockLevel = showUnlockNextLevel; //EnableScreenshots(); CheckPause(); } void OnGUI() { // Set the skin to use GUI.skin = skin; //We can reduce the draw calls from OnGUI() function by //enclosing all the contents inside a if loop like this one //draw level skin.label.normal.textColor = Color.black; Matrix4x4 svMat = GUI.matrix;//save current matrix Vector3 scaleVector = resolutionHelper.scaleVector; bool isWideScreen = resolutionHelper.isWidescreen; int width = resolutionHelper.screenWidth; int height = resolutionHelper.screenHeight; Matrix4x4 normalMatrix; Matrix4x4 wideMatrix; //we use the center matrix for the buttons wideMatrix = Matrix4x4.TRS(new Vector3( (resolutionHelper.scaleX - scaleVector.y) / 2 * width, 0, 0), Quaternion.identity, scaleVector); normalMatrix = Matrix4x4.TRS(Vector3.zero,Quaternion.identity,scaleVector); //assign normal matrix by default GUI.matrix = normalMatrix; if(Event.current.type==EventType.Repaint && !isGameOver) { DrawText(GetTranslationKey(GameConstants.MSG_LEVEL) + " " + currentLevel, messagesFontSizeSmaller +10, 20, 10,200,50); if(elapsedMissionSeconds>=1) { DrawText(elapsedMissionSeconds +" meters!" , messagesFontSizeSmaller +10, 280, 10,200,50); } } //Draw the final boss hits instead //TODO on last level show new instructions, like on first level if(IsFinalLevel()) { } if(Event.current.type==EventType.Repaint) { if(isGameStarted) { //we need this to put the play/pause at right if(isWideScreen){ GUI.matrix = wideMatrix; } else{ GUI.matrix = normalMatrix; } pausePlayRect = new Rect(width-60 ,15,48,48); if(isGamePaused) { //if not running // GUI.DrawTexture(pausePlayRect, playIcon); } //game is not paused //draw pause icon else { //GUI.DrawTexture(pausePlayRect, pauseIcon); } /*backRect = new Rect(60 ,height-160,64,64); forwardRect = new Rect(160,height - 160 ,64,64); jumpRect = new Rect(width-200,height - 160 ,64,64); GUI.DrawTexture(forwardRect, forwardButton); GUI.DrawTexture(backRect, backButton); GUI.DrawTexture(jumpRect, JumpButton);*/ } else { //Debug.Log("Not started yet"); //if null means it was destroyd, is game over //besides i cannot start with a null player, and if not a restart //neither if i'm rolling credits if(player!=null && !showUnlockLevel && !isGameComplete) { //make sure we draw this at the center of the screen if(isWideScreen){ GUI.matrix = wideMatrix; } else{ GUI.matrix = normalMatrix; } exitTextureRect = new Rect( width/2 - 100,screenHeight/2-60,200,80); GUI.DrawTexture(exitTextureRect, exitTexture); #if UNITY_ANDROID && !UNITY_EDITOR rateRect = new Rect( width/2 - 100,screenHeight/2+40,200,80); GUI.DrawTexture(rateRect, rateTexture); #endif //start playing //screenWidth //--------------------------------------------------------------------------------- /*#if UNITY_ANDROID || UNITY_IOS //GUI.Label(new Rect(width/2-69,(int)screenHeight / 3 * 2 - 15,200,40),"Leaderboards"); leaderboardsRect = new Rect(width/2-50,screenHeight / 3 * 2 + 10 ,96,96); GUI.DrawTexture(leaderboardsRect, leaderBoardTexture,ScaleMode.ScaleToFit); #endif*/ //--------------------------------------------------------------------------------- //if(highScore > 0) { //GetTranslationKey(GameConstants.MSG_HIGH_SCORE) // DrawText("High Score: " + highScore, messagesFontSizeSmaller +10,740, 10,220,40); //} } } }//end repaint //--------------------------------------------------------- //*************** CHEK TEXTURE CLICKS ********************* //--------------------------------------------------------- //before checking the clicks we put the correct matrix if(isWideScreen){ GUI.matrix = wideMatrix; } else{ GUI.matrix = normalMatrix; } //--------------------------------------------- if(!isMobilePlatform) { //desktop if(Event.current.type == EventType.MouseUp ) { if(isGameOver) { #if UNITY_ANDROID && !UNITY_EDITOR if(rateRect.Contains(Event.current.mousePosition) && player!=null) { Application.OpenURL("market://details?id=com.pcdreams.superjellytroopers"); } #endif if(exitTextureRect.Contains(Event.current.mousePosition) ) { StartGame(); } /*else if(leaderboardsRect!=null && player!=null && leaderboardsRect.Contains(Event.current.mousePosition) ) { if(socialAPIInstance.isAuthenticated) { socialAPIInstance.ShowLeaderBoards(); } else { StartCoroutine(ShowMessage(GetTranslationKey(GameConstants.MSG_GAME_CENTER_ERROR), 1.5f)); } }*/ } else { //Did i paused the game??? if(pausePlayRect.Contains(Event.current.mousePosition)) { isGamePaused = !isGamePaused; if(isGamePaused) { PauseGame(); } else { ResumeGame(); } } else if(backRect.Contains(Event.current.mousePosition)) { EnableLevelsScroll(); player.MoveBackward(); ScrollLevelsForward(); } else if(forwardRect.Contains(Event.current.mousePosition)) { EnableLevelsScroll(); player.MoveForward(); ScrollLevelsBackward(); } else if(jumpRect.Contains(Event.current.mousePosition)) { player.Jump(); } else { DisableLevelsScroll(); } } } } //if mobile platform else { //---------------------------------------------------------------- //detect touches on leaderboards //for this we need the normal matrix bool touchedLeaderBoard = false; if (Input.touches.Length ==1) { Touch touch = Input.touches[0]; if(touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled) { Vector2 fingerPos = GetFingerPosition(touch,isWideScreen); if(isGameOver) { /*#if UNITY_IOS || UNITY_ANDROID && !UNITY_EDITOR if(leaderboardsRect.Contains(fingerPos) && player!=null) { touchedLeaderBoard = true; if(socialAPIInstance.isAuthenticated) { socialAPIInstance.ShowLeaderBoards(); } else { StartCoroutine(ShowMessage(GetTranslationKey(GameConstants.MSG_GAME_CENTER_ERROR), 1.5f)); } } #endif*/ //is game over, maybe not started yet? if(exitTextureRect.Contains(fingerPos) ) { StartGame(); } #if UNITY_ANDROID && !UNITY_EDITOR if(rateRect.Contains(fingerPos) && player!=null) { Application.OpenURL("market://details?id=com.pcdreams.superjellytroopers"); } #endif } else if(pausePlayRect.Contains(fingerPos) ) { //already started //Did i paused the game??? isGamePaused = !isGamePaused; if(isGamePaused) { PauseGame(); } else { ResumeGame(); } } if(backRect.Contains(fingerPos)) { //move player back EnableLevelsScroll(); player.MoveBackward(); ScrollLevelsForward(); } else if(forwardRect.Contains(fingerPos)) { //move player forward EnableLevelsScroll(); player.MoveForward(); ScrollLevelsBackward(); } else if(jumpRect.Contains(fingerPos)) { player.Jump(); } else { player.PlayerStationary(); DisableLevelsScroll(); } } } //end if (Input.touches.Length ==1) }//else is mobile platform //******************** MOBILE TOUCHES ARE HANDLED ON UPDATE() ??? ************* //restore the matrix GUI.matrix = svMat; } void InvertParalaxScrollingDirection(int direction) { foreach(GameObject obj in paralaxLevels) { ScrollingScript scroll = obj.GetComponent<ScrollingScript>(); if(scroll!=null) { scroll.direction.x = direction; } } } void ScrollLevelsForward() { InvertParalaxScrollingDirection(1); } void ScrollLevelsBackward() { InvertParalaxScrollingDirection(-1); } void DisableLevelsScroll() { foreach(GameObject obj in paralaxLevels) { ScrollingScript scroll = obj.GetComponent<ScrollingScript>(); if(scroll!=null) { scroll.enabled = false; } } } void EnableLevelsScroll() { foreach(GameObject obj in paralaxLevels) { ScrollingScript scroll = obj.GetComponent<ScrollingScript>(); if(scroll!=null) { scroll.enabled = true; } } } /** *Get the correct finger touch position */ Vector2 GetFingerPosition(Touch touch, bool isWideScreen) { Vector2 fingerPos = new Vector2(0,0); float diference = 0f; fingerPos.y = screenHeight - (touch.position.y / Screen.height) * screenHeight; fingerPos.x = (touch.position.x / Screen.width) * screenWidth; return fingerPos; } //IEnumerator ShowMessage (string message, float delay) { /*GameObject textObj = GameObject.FindGameObjectWithTag("JellyTxt"); if(textObj!=null) { GUIText guiText = textObj.GetComponent<GUIText>(); if(guiText!=null) { guiText.text = message; guiText.enabled = true; yield return new WaitForSeconds(delay); guiText.enabled = false; } }*/ //} string GetTranslationKey(string key) { return translationManager.GetText(key); } public bool IsMobilePlatform() { return isMobilePlatform; } public bool IsIOSPlatform() { return platform == RuntimePlatform.IPhonePlayer; } public bool IsAndroidPlatform() { return platform == RuntimePlatform.Android; } public void DrawLargerText(string text) { DrawText(text,messagesFontSizeLarger); } public void DrawSmallerText(string text) { DrawText(text,messagesFontSizeSmaller); } public void DrawText(string text, int fontSize) { GUIStyle centeredStyleSmaller = GUI.skin.GetStyle("Label"); centeredStyleSmaller.alignment = TextAnchor.MiddleLeft; centeredStyleSmaller.font = messagesFont; centeredStyleSmaller.fontSize = fontSize; GUI.Label (new Rect(screenWidth/2-200, screenHeight/2, 400, 50), text); } public void DrawText(string text, int fontSize, int x, int y,int width,int height) { GUIStyle centeredStyleSmaller = GUI.skin.GetStyle("Label"); centeredStyleSmaller.alignment = TextAnchor.MiddleLeft; centeredStyleSmaller.font = messagesFont; centeredStyleSmaller.fontSize = fontSize; GUI.Label(new Rect(x, y, width, height), text); } public void DrawText(string text, int fontSize, float x, float y,int width,int height) { GUIStyle centeredStyleSmaller = GUI.skin.GetStyle("Label"); centeredStyleSmaller.alignment = TextAnchor.MiddleLeft; centeredStyleSmaller.font = messagesFont; centeredStyleSmaller.fontSize = fontSize; GUI.Label(new Rect(x, y, width, height), text); } //release banner resources void OnDestroy() { } //only spwan and shoot if player is in sight public bool IsPlayerVisible() { bool checkPlayerVisible = (player==null) ? false : player.renderer.IsVisibleFrom(Camera.main); return checkPlayerVisible; } }
/******************************************************************************* INTEL CORPORATION PROPRIETARY INFORMATION This software is supplied under the terms of a license agreement or nondisclosure agreement with Intel Corporation and may not be copied or disclosed except in accordance with the terms of that agreement Copyright(c) 2012-2014 Intel Corporation. All Rights Reserved. ******************************************************************************/ using UnityEngine; using System; using System.IO; using System.Collections.Generic; namespace RSUnityToolkit { /// <summary> /// Sense toolkit manager - this componenet is responsible for initializing the Sense SDK with the requested capabilities, according to the Options set. /// There must be one and only one instance of this script per scene. /// </summary> /// <exception cref='Exception'> /// Is thrown when the more than one instance is added to the scene /// </exception> public class SenseToolkitManager : MonoBehaviour { #region Public Static fields public static SenseToolkitManager Instance = null; public static string AssetPrefabFolder = "Assets/RSUnityToolkit/Prefabs/"; public MCTTypes.RGBQuality ColorImageQuality = MCTTypes.RGBQuality.VGA; #endregion #region Public Properties/ fields public PXCMSenseManager SenseManager = null; [SerializeField] [HideInInspector] public SenseToolkitSpeechManager SpeechManager = null; public MCTTypes.RunModes RunMode = MCTTypes.RunModes.LiveStream; public string FilePath = ""; public int NumberOfDetectedFaces = 2; public int MaxBlobsToDetect = 2; [HideInInspector] public bool Initialized; //----------------------------------------- // Output data //************ [HideInInspector] public PXCMFaceData FaceModuleOutput = null; [HideInInspector] public PXCMHandData HandDataOutput = null; [HideInInspector] public PXCMImage ImageRgbOutput = null; [HideInInspector] public PXCMImage ImageDepthOutput = null; [HideInInspector] public PXCMImage ImageMaskOutout = null; [HideInInspector] public PXCMImage ImageIROutput = null; [HideInInspector] public PXCMImage Image3DSegmentationOutput = null; [HideInInspector] public PXCMPoint3DF32[] PointCloud; [HideInInspector] public PXCMPointF32[] UvMap; [HideInInspector] public Dictionary<string,int> SpeechOutput = null; public PXCMProjection Projection; public PXCMBlobExtractor BlobExtractor; //----------------------------------------- #endregion #region Private fields private List<SenseOption> _senseOptions = new List<SenseOption>(); private pxcmStatus _sts; private PXCMCapture.Sample _captureSample; private bool _isInitBlob = false; private Dictionary<string,int> _speechCommandsRef = new Dictionary<string, int>(); private bool _speechCommandsChanged = false; private List<Action> DisposeFunctions = new List<Action>(); #endregion #region CTOR public SenseToolkitManager() : base() { /* Create a SpeechManager instance */ if (SpeechManager == null) { SpeechManager = new SenseToolkitSpeechManager(); if (SpeechManager == null) { print("Unable to create the speech pipeline instance"); } } } #endregion #region Unity's overridden methods void Awake() { if (Instance != null) { throw new UnityException("Only one instance of SenseToolkitManager in a scene is allowed."); } Instance = this; // sets default options _senseOptions.Add( new SenseOption(SenseOption.SenseOptionID.Face){ ModuleCUID = PXCMFaceModule.CUID } ); _senseOptions.Add( new SenseOption(SenseOption.SenseOptionID.Hand){ ModuleCUID = PXCMHandModule.CUID } ); _senseOptions.Add( new SenseOption(SenseOption.SenseOptionID.Object){ ModuleCUID = PXCMTracker.CUID } ); _senseOptions.Add( new SenseOption(SenseOption.SenseOptionID.VideoColorStream)); _senseOptions.Add( new SenseOption(SenseOption.SenseOptionID.VideoDepthStream)); _senseOptions.Add( new SenseOption(SenseOption.SenseOptionID.VideoIRStream)); _senseOptions.Add( new SenseOption(SenseOption.SenseOptionID.PointCloud)); _senseOptions.Add( new SenseOption(SenseOption.SenseOptionID.UVMap)); _senseOptions.Add( new SenseOption(SenseOption.SenseOptionID.Speech)); _senseOptions.Add( new SenseOption(SenseOption.SenseOptionID.VideoSegmentation){ModuleCUID = PXCM3DSeg.CUID} ); } void OnEnable() { Initialized = false; /* Create a SenseManager instance */ SenseManager = PXCMSenseManager.CreateInstance(); if (SenseManager == null) { print("Unable to create the pipeline instance"); return; } if (_speechCommandsRef.Count != 0) { SetSenseOption(SenseOption.SenseOptionID.Speech); } int numberOfEnabledModalities = 0; //Set mode according to RunMode - play from file / record / live stream if (RunMode == MCTTypes.RunModes.PlayFromFile) { //CHECK IF FILE EXISTS if (!System.IO.File.Exists(FilePath)) { Debug.LogWarning("No Filepath Set Or File Doesn't Exist, Run Mode Will Be Changed to Live Stream"); RunMode = MCTTypes.RunModes.LiveStream; } else { PXCMCaptureManager cManager = SenseManager.QueryCaptureManager(); cManager.SetFileName(FilePath, false); Debug.Log("SenseToolkitManager: Playing from file: " + FilePath); } } if (RunMode == MCTTypes.RunModes.RecordToFile) { //CHECK IF PATH string PathOnly = FilePath; while (!PathOnly[PathOnly.Length - 1].Equals('\\')) { PathOnly = PathOnly.Remove(PathOnly.Length - 1, 1); } if (!System.IO.Directory.Exists(PathOnly)) { Debug.LogWarning("No Filepath Set Or Path Doesn't Exist, Run Mode Will Be Changed to Live Stream"); RunMode = MCTTypes.RunModes.LiveStream; } else { PXCMCaptureManager cManager = SenseManager.QueryCaptureManager(); cManager.SetFileName(FilePath, true); Debug.Log("SenseToolkitManager: Recording to file: " + FilePath); } } /* Enable modalities according to the set options*/ if (IsSenseOptionSet(SenseOption.SenseOptionID.Face, true)) { SenseManager.EnableFace(); _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.Face).Initialized = true; _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.Face).Enabled = true; SetSenseOption(SenseOption.SenseOptionID.VideoColorStream); numberOfEnabledModalities++; } if (IsSenseOptionSet(SenseOption.SenseOptionID.Hand, true)) { _sts = SenseManager.EnableHand(); _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.Hand).Initialized = true; _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.Hand).Enabled = true; numberOfEnabledModalities++; } if (IsSenseOptionSet(SenseOption.SenseOptionID.Object, true)) { _sts = SenseManager.EnableTracker(); _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.Object).Initialized = true; _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.Object).Enabled = true; numberOfEnabledModalities++; } if (IsSenseOptionSet(SenseOption.SenseOptionID.Speech, true)) { if (!SpeechManager.IsInitialized) { if (SpeechManager.InitalizeSpeech()) { _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.Speech).Initialized = true; _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.Speech).Enabled = true; numberOfEnabledModalities++; } else { UnsetSenseOption(SenseOption.SenseOptionID.Speech); } } else { _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.Speech).Initialized = true; _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.Speech).Enabled = true; numberOfEnabledModalities++; } } if (IsSenseOptionSet(SenseOption.SenseOptionID.VideoDepthStream, true) || IsSenseOptionSet(SenseOption.SenseOptionID.PointCloud, true)) { SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_DEPTH, 0, 0, 0); _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.VideoDepthStream).Initialized = true; _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.VideoDepthStream).Enabled = true; numberOfEnabledModalities++; } if (IsSenseOptionSet(SenseOption.SenseOptionID.VideoIRStream, true)) { SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_IR, 0, 0, 0); _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.VideoIRStream).Initialized = true; _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.VideoIRStream).Enabled = true; numberOfEnabledModalities++; } if (IsSenseOptionSet(SenseOption.SenseOptionID.VideoColorStream, true)) { if (ColorImageQuality == MCTTypes.RGBQuality.FullHD) { SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 1920, 1080, 0); } else if (ColorImageQuality == MCTTypes.RGBQuality.HD) { SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 1280, 720, 0); } else if (ColorImageQuality == MCTTypes.RGBQuality.HalfHD) { SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 960, 540, 0); } else { SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 640, 480, 0); } _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.VideoColorStream).Initialized = true; _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.VideoColorStream).Enabled = true; numberOfEnabledModalities++; } if (IsSenseOptionSet(SenseOption.SenseOptionID.VideoSegmentation, true)) { if (ColorImageQuality == MCTTypes.RGBQuality.FullHD) { SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 1920, 1080, 0); } else if (ColorImageQuality == MCTTypes.RGBQuality.HD) { SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 1280, 720, 0); } else if (ColorImageQuality == MCTTypes.RGBQuality.HalfHD) { SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 960, 540, 0); } else { SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 640, 480, 0); } SenseManager.Enable3DSeg(); _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.VideoSegmentation).Initialized = true; _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.VideoSegmentation).Enabled = true; numberOfEnabledModalities++; } /* Initialize the execution */ _sts = SenseManager.Init(); if (_sts < pxcmStatus.PXCM_STATUS_NO_ERROR) { if (numberOfEnabledModalities > 0) { Debug.LogError("Unable to initialize all modalities"); } return; } //Set different configurations: // Face if (IsSenseOptionSet(SenseOption.SenseOptionID.Face, true)) { var faceModule = SenseManager.QueryFace(); var faceConfiguration = faceModule.CreateActiveConfiguration(); if (faceConfiguration == null) throw new UnityException("CreateActiveConfiguration returned null"); faceConfiguration.Update(); faceConfiguration.detection.isEnabled = true; faceConfiguration.detection.smoothingLevel = PXCMFaceConfiguration.SmoothingLevelType.SMOOTHING_DISABLED; faceConfiguration.landmarks.isEnabled = true; faceConfiguration.landmarks.smoothingLevel = PXCMFaceConfiguration.SmoothingLevelType.SMOOTHING_DISABLED; faceConfiguration.pose.isEnabled = true; faceConfiguration.pose.smoothingLevel = PXCMFaceConfiguration.SmoothingLevelType.SMOOTHING_DISABLED; faceConfiguration.DisableAllAlerts(); faceConfiguration.strategy = PXCMFaceConfiguration.TrackingStrategyType.STRATEGY_APPEARANCE_TIME; if ((NumberOfDetectedFaces < 1) || (NumberOfDetectedFaces > 15)) { Debug.Log("Ilegal value for Number Of Detected Faces, value is set to 1"); NumberOfDetectedFaces = 1; } faceConfiguration.detection.maxTrackedFaces = NumberOfDetectedFaces; faceConfiguration.landmarks.maxTrackedFaces = NumberOfDetectedFaces; faceConfiguration.pose.maxTrackedFaces = NumberOfDetectedFaces; PXCMFaceConfiguration.ExpressionsConfiguration expressionConfig = faceConfiguration.QueryExpressions(); expressionConfig.Enable(); expressionConfig.EnableAllExpressions(); faceConfiguration.ApplyChanges(); faceConfiguration.Dispose(); FaceModuleOutput = faceModule.CreateOutput(); UnsetSenseOption(SenseOption.SenseOptionID.VideoColorStream); } // Hand if (IsSenseOptionSet(SenseOption.SenseOptionID.Hand, true)) { PXCMHandModule handAnalysis = SenseManager.QueryHand(); PXCMHandConfiguration handConfiguration = handAnalysis.CreateActiveConfiguration(); if (handConfiguration == null) throw new UnityException("CreateActiveConfiguration returned null"); handConfiguration.Update(); handConfiguration.EnableAllGestures(); handConfiguration.EnableStabilizer(true); handConfiguration.DisableAllAlerts(); handConfiguration.EnableSegmentationImage(false); handConfiguration.ApplyChanges(); handConfiguration.Dispose(); HandDataOutput = handAnalysis.CreateOutput(); } if (IsSenseOptionSet(SenseOption.SenseOptionID.Object, true)) { if (_senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.Object).Enabled != true) { _senseOptions.Find( i => i.ID == SenseOption.SenseOptionID.Object).Enabled = true; OnDisable(); OnEnable(); } } if (IsSenseOptionSet(SenseOption.SenseOptionID.Speech, true)) { UpdateSpeechCommands(); SpeechManager.Start(); } // Create an instance for the projection & blob extractor if (Projection == null) { Projection = SenseManager.QueryCaptureManager().QueryDevice().CreateProjection(); } if (BlobExtractor == null) { SenseManager.session.CreateImpl<PXCMBlobExtractor>(out BlobExtractor); } // Set initialization flag Initialized = true; } /// <summary> /// Returns true if IvCam is used. /// </summary> public bool IsIvcam() { PXCMCapture.DeviceInfo info; SenseManager.QueryCaptureManager().device.QueryDeviceInfo(out info); if (info.model == PXCMCapture.DeviceModel.DEVICE_MODEL_IVCAM) { return true; } return false; } void Start() { } void OnDisable() { //Disposses all modules Initialized = false; if (SenseManager == null) return; DisposeFunctions.ForEach( i=> i.DynamicInvoke()); if (FaceModuleOutput != null) { FaceModuleOutput.Dispose(); FaceModuleOutput = null; } if (HandDataOutput != null) { SenseManager.PauseHand(true); HandDataOutput.Dispose(); HandDataOutput = null; } if (ImageRgbOutput != null) { ImageRgbOutput.Dispose(); ImageRgbOutput = null; } if (ImageDepthOutput != null) { ImageDepthOutput.Dispose(); ImageDepthOutput = null; } if (ImageIROutput != null) { ImageIROutput.Dispose(); ImageIROutput = null; } if (Image3DSegmentationOutput != null) { Image3DSegmentationOutput.Dispose(); Image3DSegmentationOutput = null; } if (Projection != null) { Projection.Dispose(); Projection = null; } if (BlobExtractor != null) { BlobExtractor.Dispose(); BlobExtractor = null; } UvMap = null; PointCloud = null; SenseManager.Dispose(); SenseManager = null; } void OnApplicationQuit() { OnDisable(); if (SpeechManager.IsInitialized) { SpeechManager.Dispose(); } } void Update() { //Dynamically Pause/Enable Modules int numberOfEnabledModules = 0; foreach (var option in _senseOptions) { if (option.RefCounter == 0 && option.Enabled ) { if (option.ModuleCUID > 0) { SenseManager.PauseModule(option.ModuleCUID, true); } option.Enabled = false; } else if (option.RefCounter > 0 && !option.Enabled) { if (!option.Initialized) { OnDisable(); OnEnable(); Start(); } if (option.ModuleCUID > 0) { SenseManager.PauseModule(option.ModuleCUID, false); } option.Enabled = true; } if (option.Enabled) { numberOfEnabledModules++; } } //Update Speech commands if changed if (_speechCommandsChanged) { UpdateSpeechCommands(); SpeechManager.Reset(); } // Every frame update all the data if (Initialized && numberOfEnabledModules > 0) { _sts = SenseManager.AcquireFrame(true, 100); if (_sts == pxcmStatus.PXCM_STATUS_NO_ERROR) { if (_senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoColorStream).Enabled) { if (ImageRgbOutput != null) { ImageRgbOutput.Dispose(); } if (_captureSample == null) { _captureSample = SenseManager.QuerySample(); } if (_captureSample.color != null) { ImageRgbOutput = _captureSample.color; ImageRgbOutput.QueryInstance<PXCMAddRef>().AddRef(); } } if (_senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoDepthStream).Enabled || _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.PointCloud).Enabled) { if (ImageDepthOutput != null) { ImageDepthOutput.Dispose(); } if (_captureSample == null) { _captureSample = SenseManager.QuerySample(); } if (_captureSample.depth != null) { ImageDepthOutput = _captureSample.depth; ImageDepthOutput.QueryInstance<PXCMAddRef>().AddRef(); if (!_isInitBlob) { PXCMImage.ImageInfo info = ImageDepthOutput.QueryInfo(); BlobExtractor.Init(info); BlobExtractor.SetMaxBlobs(MaxBlobsToDetect); _isInitBlob = true; } if (PointCloud == null) { PointCloud = new PXCMPoint3DF32[ImageDepthOutput.info.width * ImageDepthOutput.info.height]; } if (_senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.PointCloud).Enabled) { if (PointCloud == null) { PointCloud = new PXCMPoint3DF32[ImageDepthOutput.info.width * ImageDepthOutput.info.height]; } _sts = Projection.QueryVertices(ImageDepthOutput, PointCloud); } if (_senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.UVMap).Enabled) { if (UvMap == null) { UvMap = new PXCMPointF32[ImageDepthOutput.info.width * ImageDepthOutput.info.height]; } Projection.QueryUVMap(ImageDepthOutput, UvMap); } } } if (_senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoIRStream).Enabled) { if (ImageIROutput != null) { ImageIROutput.Dispose(); } if (_captureSample == null) { _captureSample = SenseManager.QuerySample(); } if (_captureSample.ir != null) { ImageIROutput = _captureSample.ir; ImageIROutput.QueryInstance<PXCMAddRef>().AddRef(); } } if (_senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoSegmentation).Enabled) { if (Image3DSegmentationOutput != null) { Image3DSegmentationOutput.Dispose(); } PXCM3DSeg seg = SenseManager.Query3DSeg(); if (seg != null) { Image3DSegmentationOutput = seg.AcquireSegmentedImage(); } } if (_senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Face).Enabled) { FaceModuleOutput.Update(); } if (_senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Hand).Enabled) { HandDataOutput.Update(); } _captureSample = null; SenseManager.ReleaseFrame(); } //Speech if (_senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Speech).Enabled) { SpeechManager.QueryRecognizedCommands(out SpeechOutput); } } } #endregion #region Public Methods /// <summary> /// Add the given function to an internal list and this function will be called before calling the dispose on the SenseManager. /// </summary> public void AddDisposeFunction(Action func) { DisposeFunctions.Add(func); } /// <summary> /// Determines whether the flag is already set (and has at least one reference). /// </summary> public bool IsSenseOptionSet(SenseOption.SenseOptionID flag) { return IsSenseOptionSet(flag, false); } /// <summary> /// Determines whether the flag is already set (and has at least one reference) or if it is initialized /// </summary> public bool IsSenseOptionSet(SenseOption.SenseOptionID flag, bool orInitialized) { var option = _senseOptions.Find(i => i.ID == flag); if (option == null) { return false; } if (!orInitialized) { return option.RefCounter > 0; } else { return option.Initialized || option.RefCounter > 0; } } /// <summary> /// Sets the sense option. /// </summary> /// <param name='flag'> /// Flag. /// </param> public void SetSenseOption(SenseOption.SenseOptionID flag) { var option = _senseOptions.Find(i => i.ID == flag); if (option == null) { option = new SenseOption(flag); _senseOptions.Add(option); } option.RefCounter++; } /// <summary> /// Unsets the sense option. /// </summary> /// <param name='flag'> /// Flag. /// </param> public void UnsetSenseOption(SenseOption.SenseOptionID flag) { var option = _senseOptions.Find(i => i.ID == flag); if (option == null) { option = new SenseOption(flag); _senseOptions.Add(option); } option.RefCounter--; if (option.RefCounter < 0) { option.RefCounter = 0; } } /// <summary> /// Adds a speech command. /// </summary> public bool AddSpeechCommand(string command) { if (command.Equals("")) { return false; } if (_speechCommandsRef.ContainsKey(command)) { _speechCommandsRef[command]++; } else { _speechCommandsRef.Add(command,1); _speechCommandsChanged = true; } return true; } /// <summary> /// Removes a speech command. /// </summary> public bool RemoveSpeechCommand(string command) { if (command.Equals("") || !_speechCommandsRef.ContainsKey(command)) { return false; } if (_speechCommandsRef[command] == 1) { _speechCommandsRef.Remove(command); _speechCommandsChanged = true; } else { _speechCommandsRef[command]--; } return true; } #endregion #region Private Methods private void UpdateSpeechCommands() { SpeechManager.Commands = new string[_speechCommandsRef.Count]; int i=0; foreach (KeyValuePair<string,int> cmdPair in _speechCommandsRef) { SpeechManager.Commands[i++] = cmdPair.Key; } _speechCommandsChanged = false; } #endregion } }
using System.IO; using System.Linq; using System.Threading.Tasks; using Telegram.Bot.Exceptions; using Telegram.Bot.Tests.Integ.Framework; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.InlineQueryResults; using Telegram.Bot.Types.ReplyMarkups; using Xunit; namespace Telegram.Bot.Tests.Integ.Inline_Mode { [Collection(Constants.TestCollections.InlineQuery)] [Trait(Constants.CategoryTraitName, Constants.InteractiveCategoryValue)] [TestCaseOrderer(Constants.TestCaseOrderer, Constants.AssemblyName)] public class InlineQueryTests { ITelegramBotClient BotClient => _fixture.BotClient; readonly TestsFixture _fixture; public InlineQueryTests(TestsFixture fixture) { _fixture = fixture; } [OrderedFact("Should answer inline query with an article")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Article() { await _fixture.SendTestInstructionsAsync( "1. Start an inline query\n" + "2. Wait for bot to answer it\n" + "3. Choose the answer", startInlineQuery: true ); // Wait for tester to start an inline query // This looks for an Update having a value on "inline_query" field Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); // Prepare results of the query InlineQueryResult[] results = { new InlineQueryResultArticle( id: "article:bot-api", title: "Telegram Bot API", inputMessageContent: new InputTextMessageContent("https://core.telegram.org/bots/api")) { Description = "The Bot API is an HTTP-based interface created for developers", }, }; // Answer the query await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); // Wait for tester to choose a result and send it(as a message) to the chat ( Update messageUpdate, Update chosenResultUpdate ) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Text ); Assert.Equal(MessageType.Text, messageUpdate.Message!.Type); Assert.Equal("article:bot-api", chosenResultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, chosenResultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should get message from an inline query with ViaBot property set")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Get_Message_From_Inline_Query_With_ViaBot() { await _fixture.SendTestInstructionsAsync( "1. Start an inline query\n" + "2. Wait for bot to answer it\n" + "3. Choose the answer", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); InlineQueryResult[] results = { new InlineQueryResultArticle( id: "article:bot-api", title: "Telegram Bot API", inputMessageContent: new InputTextMessageContent("https://core.telegram.org/bots/api")) { Description = "The Bot API is an HTTP-based interface created for developers", }, }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); Update messageUpdate = ( await _fixture.UpdateReceiver.GetUpdatesAsync( predicate: update => update.Message!.ViaBot is not null, updateTypes: new[] { UpdateType.Message }) ).First(); Assert.Equal(MessageType.Text, messageUpdate.Message.Type); Assert.NotNull(messageUpdate.Message.ViaBot); Assert.Equal(_fixture.BotUser.Id, messageUpdate.Message.ViaBot.Id); } [OrderedFact("Should answer inline query with a contact")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Contact() { await _fixture.SendTestInstructionsAsync( "Staring the inline query with this message...", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "contact:john-doe"; InlineQueryResult[] results = { new InlineQueryResultContact(id: resultId, phoneNumber: "+1234567", firstName: "John") { LastName = "Doe" } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Contact ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Contact, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should answer inline query with a location")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Location() { await _fixture.SendTestInstructionsAsync( "Staring the inline query with this message...", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "location:hobitton"; InlineQueryResult[] results = { new InlineQueryResultLocation( id: resultId, latitude: -37.8721897f, longitude: 175.6810213f, title: "Hobbiton Movie Set") }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Location ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Location, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should answer inline query with a venue")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Venue() { await _fixture.SendTestInstructionsAsync( "Staring the inline query with this message...", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "venue:hobbiton"; InlineQueryResult[] results = { new InlineQueryResultVenue( id: resultId, latitude: -37.8721897f, longitude: 175.6810213f, title: "Hobbiton Movie Set", address: "501 Buckland Rd, Hinuera, Matamata 3472, New Zealand") }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Venue ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Venue, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should answer inline query with a photo")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Photo() { await _fixture.SendTestInstructionsAsync( "Staring the inline query with this message...", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "photo:rainbow-girl"; const string url = "https://cdn.pixabay.com/photo/2017/08/30/12/45/girl-2696947_640.jpg"; const string caption = "Rainbow Girl"; InlineQueryResult[] results = { new InlineQueryResultPhoto(id: resultId, photoUrl: url, thumbUrl: url) { Caption = caption } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Photo ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Photo, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); Assert.Equal(caption, messageUpdate.Message.Caption); } [OrderedFact("Should send a photo and answer inline query with a cached photo using its file_id")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Photo() { Message photoMessage; await using (FileStream stream = System.IO.File.OpenRead(Constants.PathToFile.Photos.Apes)) { photoMessage = await BotClient.SendPhotoAsync( chatId: _fixture.SupergroupChat, photo: stream, replyMarkup: (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "photo:apes"; const string caption = "Apes smoking shisha"; InlineQueryResult[] results = { new InlineQueryResultCachedPhoto( id: resultId, photoFileId: photoMessage.Photo!.First().FileId) { Caption = caption } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Photo ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Photo, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); Assert.Equal(caption, messageUpdate.Message.Caption); } [OrderedFact("Should answer inline query with a video")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Video() { await _fixture.SendTestInstructionsAsync( "Staring the inline query with this message...", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "sunset_video"; InlineQueryResult[] results = { new InlineQueryResultVideo( id: resultId, videoUrl: "https://pixabay.com/en/videos/download/video-10737_medium.mp4", thumbUrl: "https://i.vimeocdn.com/video/646283246_640x360.jpg", title: "Sunset Landscape") { Description = "A beautiful scene" } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Video ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Video, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should answer inline query with a YouTube video (HTML page)")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_HTML_Video() { // ToDo exception when input_message_content not specified. Bad Request: SEND_MESSAGE_MEDIA_INVALID await _fixture.SendTestInstructionsAsync( "Staring the inline query with this message...", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "youtube_video"; InlineQueryResult[] results = { new InlineQueryResultVideo( id: resultId, videoUrl: "https://www.youtube.com/watch?v=1S0CTtY8Qa0", thumbUrl: "https://www.youtube.com/watch?v=1S0CTtY8Qa0", title: "Rocket Launch", inputMessageContent: new InputTextMessageContent("[Rocket Launch](https://www.youtube.com/watch?v=1S0CTtY8Qa0)") { ParseMode = ParseMode.Markdown } ) }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Text ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Text, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should send a video and answer inline query with a cached video using its file_id")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Video() { // Video from https://pixabay.com/en/videos/fireworks-rocket-new-year-s-eve-7122/ Message videoMessage = await BotClient.SendVideoAsync( chatId: _fixture.SupergroupChat, video: "https://pixabay.com/en/videos/download/video-7122_medium.mp4", replyMarkup: (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "fireworks_video"; InlineQueryResult[] results = { new InlineQueryResultCachedVideo( id: resultId, videoFileId: videoMessage.Video!.FileId, title: "New Year's Eve Fireworks") { Description = "2017 Fireworks in Germany" } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Video ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Video, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should answer inline query with an audio")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Audio() { await _fixture.SendTestInstructionsAsync( "Staring the inline query with this message...", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "audio_result"; InlineQueryResult[] results = { new InlineQueryResultAudio( id: resultId, audioUrl: "https://upload.wikimedia.org/wikipedia/commons/transcoded/b/bb/Test_ogg_mp3_48kbps.wav/Test_ogg_mp3_48kbps.wav.mp3", title: "Test ogg mp3") { Performer = "Shishirdasika", AudioDuration = 25 } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Audio ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Audio, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should send an audio and answer inline query with a cached audio using its file_id")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SendAudio)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Audio() { Message audioMessage; await using (FileStream stream = System.IO.File.OpenRead(Constants.PathToFile.Audio.CantinaRagMp3)) { audioMessage = await BotClient.SendAudioAsync( chatId: _fixture.SupergroupChat, audio: stream, performer: "Jackson F. Smith", duration: 201, replyMarkup: (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "audio_result"; InlineQueryResult[] results = { new InlineQueryResultCachedAudio( id: resultId, audioFileId: audioMessage.Audio!.FileId) { Caption = "Jackson F. Smith - Cantina Rag" } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Audio ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Audio, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should answer inline query with an audio")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Voice() { await _fixture.SendTestInstructionsAsync( "Staring the inline query with this message...", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "voice_result"; InlineQueryResult[] results = { new InlineQueryResultVoice( id: resultId, voiceUrl: "http://www.vorbis.com/music/Hydrate-Kenny_Beltrey.ogg", title: "Hydrate - Kenny Beltrey") { Caption = "Hydrate - Kenny Beltrey", VoiceDuration = 265 } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Voice ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Voice, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should send an audio and answer inline query with a cached audio using its file_id")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Voice() { Message voiceMessage; await using (FileStream stream = System.IO.File.OpenRead(Constants.PathToFile.Audio.TestOgg)) { voiceMessage = await BotClient.SendVoiceAsync( chatId: _fixture.SupergroupChat, voice: stream, duration: 24, replyMarkup: (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "voice_result"; InlineQueryResult[] results = { new InlineQueryResultCachedVoice( id: resultId, fileId: voiceMessage.Voice!.FileId, title: "Test Voice" ) }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Voice ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Voice, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should answer inline query with a document")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Document() { await _fixture.SendTestInstructionsAsync( "Staring the inline query with this message...", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "document_result"; InlineQueryResult[] results = { new InlineQueryResultDocument( id: resultId, documentUrl: "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", title: "Dummy PDF File", mimeType: "application/pdf") { Caption = "Dummy PDF File", Description = "Dummy PDF File for testing", } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Document ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Document, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should send a document and answer inline query with a cached document using its file_id")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Document() { Message documentMessage; await using (FileStream stream = System.IO.File.OpenRead(Constants.PathToFile.Documents.Hamlet)) { documentMessage = await BotClient.SendDocumentAsync( chatId: _fixture.SupergroupChat, document: stream, replyMarkup: (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query") ); } Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "document_result"; InlineQueryResult[] results = { new InlineQueryResultCachedDocument( id: resultId, documentFileId: documentMessage.Document!.FileId, title: "Test Document") { Caption = "The Tragedy of Hamlet, Prince of Denmark", Description = "Sample PDF Document", } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Document ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Document, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should answer inline query with a gif")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Gif() { await _fixture.SendTestInstructionsAsync( "Staring the inline query with this message...", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "gif_result"; InlineQueryResult[] results = { new InlineQueryResultGif( id: resultId, gifUrl: "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif", thumbUrl: "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif") { Caption = "Rotating Earth", GifDuration = 4, GifHeight = 400, GifWidth = 400, Title = "Rotating Earth", ThumbMimeType = "image/gif", } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Document ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Document, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should send a gif and answer inline query with a cached gif using its file_id")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Gif() { Message gifMessage = await BotClient.SendDocumentAsync( chatId: _fixture.SupergroupChat, document: "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif", replyMarkup: (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query")); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "gif_result"; InlineQueryResult[] results = { new InlineQueryResultCachedGif( id: resultId, gifFileId: gifMessage.Document!.FileId) { Caption = "Rotating Earth", } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Document ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Document, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should answer inline query with an mpeg4 gif")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Mpeg4Gif() { await _fixture.SendTestInstructionsAsync( "Staring the inline query with this message...", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "mpeg4_gif_result"; InlineQueryResult[] results = { new InlineQueryResultMpeg4Gif( id: resultId, mpeg4Url: "https://pixabay.com/en/videos/download/video-10737_medium.mp4", thumbUrl: "https://i.vimeocdn.com/video/646283246_640x360.jpg") { Caption = "A beautiful scene", }, }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Video ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Video, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should send an mpeg4 gif and answer inline query with a cached mpeg4 gif using its file_id")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Mpeg4Gif() { Message gifMessage = await BotClient.SendDocumentAsync( chatId: _fixture.SupergroupChat, document: "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif", replyMarkup: (InlineKeyboardMarkup)InlineKeyboardButton .WithSwitchInlineQueryCurrentChat("Start inline query")); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "mpeg4_gif_result"; InlineQueryResult[] results = { new InlineQueryResultCachedMpeg4Gif( id: resultId, mpeg4FileId: gifMessage.Document!.FileId) { Caption = "Rotating Earth", } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Document ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Document, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should answer inline query with a cached sticker using its file_id")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.GetStickerSet)] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Cached_Sticker() { await _fixture.SendTestInstructionsAsync( "Staring the inline query with this message...", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); StickerSet stickerSet = await BotClient.GetStickerSetAsync("EvilMinds"); const string resultId = "sticker_result"; InlineQueryResult[] results = { new InlineQueryResultCachedSticker(id: resultId, stickerFileId: stickerSet.Stickers[0].FileId) }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Sticker ); Update resultUpdate = chosenResultUpdate; Assert.Equal(MessageType.Sticker, messageUpdate.Message!.Type); Assert.Equal(resultId, resultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should answer inline query with a photo with markdown encoded caption")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Answer_Inline_Query_With_Photo_With_Markdown_Encoded_Caption() { await _fixture.SendTestInstructionsAsync( "Staring the inline query with this message...", startInlineQuery: true ); Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); const string resultId = "photo:rainbow-girl-caption"; const string url = "https://cdn.pixabay.com/photo/2017/08/30/12/45/girl-2696947_640.jpg"; const string photoCaption = "Rainbow Girl"; InlineQueryResult[] results = { new InlineQueryResultPhoto(id: resultId, photoUrl: url, thumbUrl: url) { Caption = $"*{photoCaption}*", ParseMode = ParseMode.Markdown } }; await BotClient.AnswerInlineQueryAsync( inlineQueryId: iqUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ); (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates( chatId: _fixture.SupergroupChat.Id, messageType: MessageType.Photo ); Assert.Equal(MessageType.Photo, messageUpdate.Message!.Type); Assert.Equal(photoCaption, messageUpdate.Message.Caption); Assert.Equal(MessageEntityType.Bold, messageUpdate.Message.CaptionEntities!.Single().Type); Assert.Equal(UpdateType.ChosenInlineResult, chosenResultUpdate.Type); Assert.Equal(resultId, chosenResultUpdate.ChosenInlineResult!.ResultId); Assert.Equal(iqUpdate.InlineQuery.Query, chosenResultUpdate.ChosenInlineResult.Query); } [OrderedFact("Should throw exception when answering an inline query after 10 seconds")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.AnswerInlineQuery)] public async Task Should_Throw_Exception_When_Answering_Late() { await _fixture.SendTestInstructionsAsync( "Write an inline query that I'll never answer!", startInlineQuery: true ); Update queryUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync(); InlineQueryResult[] results = { new InlineQueryResultArticle( id: "article:bot-api", title: "Telegram Bot API", inputMessageContent: new InputTextMessageContent("https://core.telegram.org/bots/api")) { Description = "The Bot API is an HTTP-based interface created for developers", }, }; await Task.Delay(10_000); ApiRequestException exception = await Assert.ThrowsAsync<ApiRequestException>(() => BotClient.AnswerInlineQueryAsync( inlineQueryId: queryUpdate.InlineQuery!.Id, results: results, cacheTime: 0 ) ); Assert.Equal("Bad Request: query is too old and response timeout expired or query ID is invalid", exception.Message); Assert.Equal(400, exception.ErrorCode); } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using DeOps.Implementation; using DeOps.Implementation.Dht; using DeOps.Implementation.Transport; namespace DeOps.Interface.Tools { /// <summary> /// Summary description for GraphForm. /// </summary> public class GraphForm : DeOps.Interface.CustomIconForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; OpCore Core; DhtNetwork Network; DhtRouting Routing; Bitmap DisplayBuffer; bool Redraw; public delegate void UpdateGraphHandler(); public UpdateGraphHandler UpdateGraph; public static void Show(DhtNetwork network) { var form = new GraphForm(network); form.Show(); form.Activate(); } public GraphForm(DhtNetwork network) { // // Required for Windows Form Designer support // InitializeComponent(); Network = network; Core = Network.Core; Routing = Network.Routing; Network.UpdateBandwidthGraph += AsyncUpdateGraph; Text = "Graph (" + Network.GetLabel() + ")"; Redraw = true; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // GraphForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 266); this.DoubleBuffered = true; this.Name = "GraphForm"; this.Text = "Graph"; this.Paint += new System.Windows.Forms.PaintEventHandler(this.GraphForm_Paint); this.Closing += new System.ComponentModel.CancelEventHandler(this.GraphForm_Closing); this.Resize += new System.EventHandler(this.GraphForm_Resize); this.ResumeLayout(false); } #endregion private void GraphForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { if(ClientSize.Width == 0 || ClientSize.Height == 0) return; if(DisplayBuffer == null ) DisplayBuffer = new Bitmap(ClientSize.Width, ClientSize.Height); if( !Redraw ) { e.Graphics.DrawImage(DisplayBuffer, 0, 0); return; } Redraw = false; // background Graphics buffer = Graphics.FromImage(DisplayBuffer); buffer.Clear(Color.DarkBlue); buffer.SmoothingMode = SmoothingMode.AntiAlias; // back black ellipse Point centerPoint = new Point(ClientSize.Width / 2, ClientSize.Height / 2); int maxRadius = (ClientSize.Height > ClientSize.Width) ? ClientSize.Width / 2 : ClientSize.Height / 2; maxRadius -= 5; buffer.FillEllipse( new SolidBrush(Color.Black), GetBoundingBox(centerPoint, maxRadius)); uint localID = IDto32(Network.Local.UserID); List<Rectangle> contactPoints = new List<Rectangle>(); List<Rectangle> cachePoints = new List<Rectangle>(); // draw circles int i = 0; float sweepAngle = 360; Pen orangePen = new Pen(Color.Orange, 2); int arcs = 0; int maxLevels = 10; int drawBuckets = Routing.BucketList.Count > maxLevels ? maxLevels : Routing.BucketList.Count; lock(Routing.BucketList) foreach(DhtBucket bucket in Routing.BucketList) { if (sweepAngle < 0.1 || i >= maxLevels) break; // draw lines if (!bucket.Last) { int rad = maxRadius * i / drawBuckets; uint lowpos = localID >> (32 - i); lowpos = lowpos << (32 - i); uint highpos = lowpos | ((uint)1 << 31 - i); float startAngle = 360 * ((float)lowpos / (float)uint.MaxValue); if (rad > 0) { arcs++; buffer.DrawArc(orangePen, GetBoundingBox(centerPoint, rad), startAngle, sweepAngle); buffer.DrawLine(orangePen, GetCircumPoint(centerPoint, rad, lowpos), GetCircumPoint(centerPoint, maxRadius, lowpos)); buffer.DrawLine(orangePen, GetCircumPoint(centerPoint, rad, highpos), GetCircumPoint(centerPoint, maxRadius, highpos)); } else buffer.DrawLine(orangePen, GetCircumPoint(centerPoint, maxRadius, 0), GetCircumPoint(centerPoint, maxRadius, uint.MaxValue / 2)); // draw text lowpos = localID >> (31 - i); highpos = (lowpos + 1) << (31 - i); lowpos = lowpos << (31 - i); Point textPoint = GetCircumPoint(centerPoint, rad + 10, lowpos + (highpos - lowpos) / 2); if ((localID & ((uint)1 << (31 - i))) > 0) buffer.DrawString("1", new Font(FontFamily.GenericSansSerif, 8, FontStyle.Bold), new SolidBrush(Color.White), textPoint); else buffer.DrawString("0", new Font(FontFamily.GenericSansSerif, 8, FontStyle.Bold), new SolidBrush(Color.White), textPoint); } foreach(DhtContact contact in bucket.ContactList) { contactPoints.Add(GetBoundingBox(GetCircumPoint(centerPoint, maxRadius, IDto32(contact.UserID)), 4)); if(Routing.InCacheArea(contact.UserID)) cachePoints.Add(GetBoundingBox(GetCircumPoint(centerPoint, maxRadius, IDto32(contact.UserID)), 1)); } sweepAngle /= 2; i++; } // draw contacts foreach(Rectangle rect in contactPoints) buffer.FillEllipse(new SolidBrush(Color.White), rect); foreach (Rectangle rect in cachePoints) buffer.FillEllipse(new SolidBrush(Color.Black), rect); // draw proxies lock(Network.TcpControl.SocketList) foreach (TcpConnect connection in Network.TcpControl.SocketList) { if(connection.Proxy == ProxyType.Server) buffer.FillEllipse(new SolidBrush(Color.Green), GetBoundingBox(GetCircumPoint(centerPoint, maxRadius, IDto32(connection.UserID)), 4)); if(connection.Proxy == ProxyType.ClientNAT || connection.Proxy == ProxyType.ClientBlocked) buffer.FillEllipse(new SolidBrush(Color.Red), GetBoundingBox(GetCircumPoint(centerPoint, maxRadius, IDto32(connection.UserID)), 4)); } // draw self buffer.FillEllipse(new SolidBrush(Color.Yellow), GetBoundingBox(GetCircumPoint(centerPoint, maxRadius, localID), 4)); // Copy buffer to display e.Graphics.DrawImage(DisplayBuffer, 0, 0); } private void GraphForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { Network.UpdateBandwidthGraph -= AsyncUpdateGraph; } private void GraphForm_Resize(object sender, System.EventArgs e) { if(ClientSize.Width > 0 && ClientSize.Height > 0) { DisplayBuffer = new Bitmap(ClientSize.Width, ClientSize.Height); Redraw = true; Invalidate(); } } public void AsyncUpdateGraph() { Redraw = true; Invalidate(); } Rectangle GetBoundingBox(Point center, int rad) { return new Rectangle(center.X - rad, center.Y - rad, rad * 2, rad * 2); } Point GetCircumPoint(Point center, int rad, uint position) { double fraction = (double) position / (double) uint.MaxValue; int xPos = (int) ((double) rad * Math.Cos( fraction * 2*Math.PI)) + center.X; int yPos = (int) ((double) rad * Math.Sin( fraction * 2*Math.PI)) + center.Y; return new Point(xPos, yPos); } uint IDto32(UInt64 id) { return (uint)(id >> 32); } } }
using System; using Gtk; using System.IO; using Moscrif.IDE.Controls; using MessageDialogs = Moscrif.IDE.Controls.MessageDialog; using Moscrif.IDE.Tool; using Moscrif.IDE.Devices; using Moscrif.IDE.Iface.Entities; namespace Moscrif.IDE.Option { internal class EmulatorOptionsPanel : OptionsPanel { DevicesOptionsWidget widget; public override Widget CreatePanelWidget() { return widget = new DevicesOptionsWidget(ParentDialog); } public override void ShowPanel() { widget.ShowWidget(); } public override void ApplyChanges() { widget.Store(); } public override bool ValidateChanges() { return widget.Valid(); } public override void Initialize(PreferencesDialog dialog, object dataObject) { base.Initialize(dialog, dataObject); } public override string Label { get { return MainClass.Languages.Translate("emulator_f1"); }//Devices } public override string Icon { get { return "emulator.png"; }//emulator-skin.png } } public partial class DevicesOptionsWidget : Gtk.Bin { Gtk.ListStore fileListStore = new Gtk.ListStore(typeof(string), typeof(string),typeof(EmulatorDisplay),typeof(string)); Gtk.ListStore resolStore = new Gtk.ListStore(typeof(string),typeof(int), typeof(string),typeof(string),typeof(Rule)); private bool isChange = false; EmulatorDisplay selectedResolDisplay; TreeIter selectedTreeIter = new TreeIter(); Gtk.Window parentWindow; //table1 public DevicesOptionsWidget(Gtk.Window parent) { parentWindow = parent; this.Build(); //ComboBox cbResolution = new ComboBox(); //table1.Attach(cbResolution,1,2,0,1); CellRendererText textRenderer = new CellRendererText(); //cbResolution.PackStart(textRenderer, true); cbResolution.AddAttribute(textRenderer, "text", 0); cbResolution.Model=resolStore; tvFiles.AppendColumn(MainClass.Languages.Translate("file"), new Gtk.CellRendererText(), "text", 0); tvFiles.AppendColumn(MainClass.Languages.Translate("path"), new Gtk.CellRendererText(), "text", 1); string[] listFi = Directory.GetFiles(MainClass.Paths.DisplayDir, "*.ini"); foreach (string fi in listFi){ EmulatorDisplay dd = new EmulatorDisplay(fi); if (dd.Load()){ fileListStore.AppendValues(System.IO.Path.GetFileName(fi),fi,dd); } } foreach (Rule rl in MainClass.Settings.Resolution.Rules ){ resolStore.AppendValues(String.Format("{0} ({1}x{2})",rl.Name,rl.Width,rl.Height),rl.Id,rl.Name,rl.Specific,rl); } tvFiles.Model = fileListStore; tvFiles.Selection.Changed += delegate(object sender, EventArgs e) { if(isChange){ Save(true); } selectedResolDisplay = GetSelectedDevicesDisplay(); if (selectedResolDisplay == null ) return; sbHeight.Value = selectedResolDisplay.Height; sbWidth.Value =selectedResolDisplay.Width; entTitle.Text =selectedResolDisplay.Title; entAuthor.Text =selectedResolDisplay.Author; entUrl.Text =selectedResolDisplay.Url; chbTablet.Active =selectedResolDisplay.Tablet; Rule rlr = MainClass.Settings.Resolution.Rules.Find(x=>x.Height==selectedResolDisplay.Height && x.Width== selectedResolDisplay.Width); if(rlr != null){ TreeIter ti = new TreeIter(); bool isFind = false; resolStore.Foreach((model, path, iterr) => { Rule ruleIter = (Rule)resolStore.GetValue(iterr, 4); if (ruleIter == rlr){ ti = iterr; isFind = true; return true; } return false; }); if(isFind) cbResolution.SetActiveIter(ti); else cbResolution.Active =0; } isChange = false; }; cbResolution.Changed += delegate(object sender, EventArgs e) { TreeIter ti = new TreeIter(); if(cbResolution.GetActiveIter(out ti)){ Rule ruleIter = (Rule)resolStore.GetValue(ti, 4); sbHeight.Value= ruleIter.Height; sbWidth.Value= ruleIter.Width; } }; } public void ShowWidget(){ isChange = false; TreeSelection ts = tvFiles.Selection; TreePath[] tp = ts.GetSelectedRows(); fileListStore.Clear(); string[] listFi = Directory.GetFiles(MainClass.Paths.DisplayDir, "*.ini"); foreach (string fi in listFi){ EmulatorDisplay dd = new EmulatorDisplay(fi); if (dd.Load()){ fileListStore.AppendValues(System.IO.Path.GetFileName(fi),fi,dd); } } resolStore.Clear(); foreach (Rule rl in MainClass.Settings.Resolution.Rules ){ resolStore.AppendValues(String.Format("{0} ({1}x{2})",rl.Name,rl.Width,rl.Height),rl.Id,rl.Name,rl.Specific,rl); } isChange = false; if (tp.Length < 1){ TreeIter ti = new TreeIter(); if(fileListStore.GetIterFirst(out ti)){ ts.SelectIter(ti); } } else { ts.SelectPath(tp[0]); } } public void Store() { } public bool Valid() { if(isChange){ Save(true); } return true; } protected virtual void OnBtnAddClicked(object sender, System.EventArgs e) { EntryDialog ed = new EntryDialog("", MainClass.Languages.Translate("new_resolution_name"),parentWindow); int result = ed.Run(); if (result == (int)ResponseType.Ok) { if (!String.IsNullOrEmpty(ed.TextEntry)) { string nameFile = MainClass.Tools.RemoveDiacritics(ed.TextEntry); string newFile = System.IO.Path.Combine(MainClass.Paths.DisplayDir, nameFile + ".ini"); /*if (File.Exists(newFile)) { MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, "Error", "File cannot is create becaus is exist!", MessageType.Error); ms.ShowDialog(); return; }*/ try { EmulatorDisplay dd= EmulatorDisplay.Create(newFile); if (dd!= null){ TreeIter ti = fileListStore.AppendValues(System.IO.Path.GetFileName(newFile), newFile,dd); tvFiles.Selection.SelectIter(ti); } //File.Create(newFile); } catch (Exception ex) { MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, "Error", ex.Message, MessageType.Error,parentWindow); ms.ShowDialog(); return; } } } ed.Destroy(); } protected virtual void OnBtnRemoveClicked(object sender, System.EventArgs e) { TreeSelection ts = tvFiles.Selection; TreeIter ti = new TreeIter(); ts.GetSelected(out ti); TreePath[] tp = ts.GetSelectedRows(); if (tp.Length < 1) return ; EmulatorDisplay dd = (EmulatorDisplay)tvFiles.Model.GetValue(ti, 2); MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.YesNo, MainClass.Languages.Translate("question_delete_file", dd.FilePath), "", Gtk.MessageType.Question,parentWindow); int result = md.ShowDialog(); if (result != (int)Gtk.ResponseType.Yes) return; if (!System.IO.File.Exists(dd.FilePath )) return; try { //fileListStore fileListStore.SetValue(ti,2,null); fileListStore.Remove(ref ti); System.IO.File.Delete(dd.FilePath); } catch { return; } } private EmulatorDisplay GetSelectedDevicesDisplay() { TreeSelection ts = tvFiles.Selection; TreeIter ti = new TreeIter(); ts.GetSelected(out ti); TreePath[] tp = ts.GetSelectedRows(); if (tp.Length < 1) return null; selectedTreeIter = ti; return (EmulatorDisplay)tvFiles.Model.GetValue(ti, 2); } private void Save(bool question){ if(question){ MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.YesNo, MainClass.Languages.Translate("question_save_resolution", selectedResolDisplay.Title), MainClass.Languages.Translate("changes_will_be_lost"), Gtk.MessageType.Question,parentWindow); int result = md.ShowDialog(); if (result != (int)Gtk.ResponseType.Yes){ isChange = false; return; } } /*TreeSelection ts = tvFiles.Selection; TreeIter ti = new TreeIter(); ts.GetSelected(out ti); TreePath[] tp = ts.GetSelectedRows(); if (tp.Length < 1) return ; ResolutionDisplay dd= (ResolutionDisplay)tvFiles.Model.GetValue(ti, 2); */ if (selectedResolDisplay == null ) return; selectedResolDisplay.Height=(int)sbHeight.Value; selectedResolDisplay.Width=(int)sbWidth.Value; selectedResolDisplay.Title = String.IsNullOrEmpty(entTitle.Text)?" ":entTitle.Text; selectedResolDisplay.Author=String.IsNullOrEmpty(entAuthor.Text)?" ":entAuthor.Text; selectedResolDisplay.Url=String.IsNullOrEmpty(entUrl.Text)?" ":entUrl.Text; selectedResolDisplay.Tablet= chbTablet.Active; selectedResolDisplay.Save(); fileListStore.SetValue(selectedTreeIter,2,selectedResolDisplay); //fileListStore.SetValue(ti,2,dd); isChange = false; } protected virtual void OnBtnSaveClicked(object sender, System.EventArgs e) { Save(false); /*TreeSelection ts = tvFiles.Selection; TreeIter ti = new TreeIter(); ts.GetSelected(out ti); TreePath[] tp = ts.GetSelectedRows(); if (tp.Length < 1) return ; ResolutionDisplay dd= (ResolutionDisplay)tvFiles.Model.GetValue(ti, 2); if (dd == null ) return; dd.Height=(int)sbHeight.Value; dd.Width=(int)sbWidth.Value; dd.Title = String.IsNullOrEmpty(entTitle.Text)?" ":entTitle.Text; dd.Author=String.IsNullOrEmpty(entAuthor.Text)?" ":entAuthor.Text; dd.Url=String.IsNullOrEmpty(entUrl.Text)?" ":entUrl.Text; dd.Save(); fileListStore.SetValue(ti,2,dd);*/ } protected void OnEntTitleChanged (object sender, System.EventArgs e) { isChange = true; } protected void OnEntAuthorChanged (object sender, System.EventArgs e) { isChange = true; } protected void OnEntUrlChanged (object sender, System.EventArgs e) { isChange = true; } protected void OnCbResolutionChanged (object sender, System.EventArgs e) { isChange = true; } protected void OnChbTabletToggled (object sender, System.EventArgs e) { isChange = true; } } }
using DCKinc.customization; using DCKinc.AAcustomization; using DCKinc.WCcustomization; using KSP.UI.Screens; using System.Collections.Generic; using UnityEngine; namespace DCKinc { [KSPAddon(KSPAddon.Startup.EditorAny, false)] class DCKPaintshop : MonoBehaviour { public static DCKPaintshop Instance = null; private ApplicationLauncherButton toolbarButton = null; private bool showWindow = false; private Rect windowRect; void Awake() { } void Start() { Instance = this; windowRect = new Rect(Screen.width - 215, Screen.height - 300, 173, 100); //default size and coordinates, change as suitable AddToolbarButton(); } private void OnDestroy() { if (toolbarButton) { ApplicationLauncher.Instance.RemoveModApplication(toolbarButton); toolbarButton = null; } } void AddToolbarButton() { string textureDir = "DCKinc/Plugin/"; if (toolbarButton == null) { Texture buttonTexture = GameDatabase.Instance.GetTexture(textureDir + "DCK_armor", false); //texture to use for the button toolbarButton = ApplicationLauncher.Instance.AddModApplication(ShowToolbarGUI, HideToolbarGUI, Dummy, Dummy, Dummy, Dummy, ApplicationLauncher.AppScenes.SPH | ApplicationLauncher.AppScenes.VAB, buttonTexture); } } public void ShowToolbarGUI() { showWindow = true; } public void HideToolbarGUI() { showWindow = false; } void Dummy() { } void OnGUI() { if (showWindow) { windowRect = GUI.Window(this.GetInstanceID(), windowRect, DCKWindow, "DCK Paintshop", HighLogic.Skin.window); //change title as suitable } } void DCKWindow(int windowID) { if (GUI.Button(new Rect(10, 25, 75, 20), "DCK Prev", HighLogic.Skin.button)) //change rect here for button size, position and text { SendEventDCK(false); } if (GUI.Button(new Rect(90, 25, 75, 20), "DCK Next", HighLogic.Skin.button)) //change rect here for button size, position and text { SendEventDCK(true); } if (GUI.Button(new Rect(10, 50, 75, 20), "Next Tire", HighLogic.Skin.button)) //change rect here for button size, position and text { SendEventDCKWC(true); } if (GUI.Button(new Rect(90, 50, 75, 20), "Armor", HighLogic.Skin.button)) //change rect here for button size, position and text { SendEventDCKAA(true); } if (GUI.Button(new Rect(10, 75, 75, 20), "Deploy", HighLogic.Skin.button)) //change rect here for button size, position and text { shieldToggle(); } if (GUI.Button(new Rect(90, 75, 75, 20), "Shields", HighLogic.Skin.button)) //change rect here for button size, position and text { SendEventDCKShields(true); } GUI.DragWindow(); } [KSPField(isPersistant = true, guiActive = true, guiName = "Shields")] public bool shieldsEnabled; public void shieldToggle() { if (!shieldsEnabled) { EnableShields(); } else { DisableShields(); } } public void sanityCheck() { if (HighLogic.LoadedSceneIsFlight) { } } public void EnableShields() { deployShields(); shieldsEnabled = true; } public void DisableShields() { retractShields(); shieldsEnabled = false; } public void deployShields() { Part root = EditorLogic.RootPart; if (!root) return; // find all ModuleDeployableRadiator modules on all parts List<ModuleDeployableRadiator> shieldParts = new List<ModuleDeployableRadiator>(200); foreach (Part p in EditorLogic.fetch.ship.Parts) { shieldParts.AddRange(p.FindModulesImplementing<ModuleDeployableRadiator>()); } foreach (ModuleDeployableRadiator shieldPart in shieldParts) { shieldPart.Extend(); } } public void retractShields() { Part root = EditorLogic.RootPart; if (!root) return; // find all ModuleDeployableRadiator modules on all parts List<ModuleDeployableRadiator> shieldParts = new List<ModuleDeployableRadiator>(200); foreach (Part p in EditorLogic.fetch.ship.Parts) { shieldParts.AddRange(p.FindModulesImplementing<ModuleDeployableRadiator>()); } foreach (ModuleDeployableRadiator shieldPart in shieldParts) { shieldPart.Retract(); } } void SendEventDCKShields(bool next) //true: next texture, false: previous texture { Part root = EditorLogic.RootPart; if (!root) return; // find all DCKtextureswitch2 modules on all parts List<DCKStextureswitch2> shieldParts = new List<DCKStextureswitch2>(200); foreach (Part p in EditorLogic.fetch.ship.Parts) { shieldParts.AddRange(p.FindModulesImplementing<DCKStextureswitch2>()); } foreach (DCKStextureswitch2 shieldPart in shieldParts) { shieldPart.updateSymmetry = false; //FIX symmetry problems because DCK also applies its own logic here // send previous or next command if (next) shieldPart.nextTextureEvent(); else shieldPart.previousTextureEvent(); } } void SendEventDCK(bool next) //true: next texture, false: previous texture { Part root = EditorLogic.RootPart; if (!root) return; // find all DCKtextureswitch2 modules on all parts List<DCKtextureswitch2> dckParts = new List<DCKtextureswitch2>(200); foreach (Part p in EditorLogic.fetch.ship.Parts) { dckParts.AddRange(p.FindModulesImplementing<DCKtextureswitch2>()); } foreach (DCKtextureswitch2 dckPart in dckParts) { dckPart.updateSymmetry = false; //FIX symmetry problems because DCK also applies its own logic here // send previous or next command if (next) dckPart.nextTextureEvent(); else dckPart.previousTextureEvent(); } } void SendEventDCKWC(bool next) //true: next texture, false: previous texture { Part root = EditorLogic.RootPart; if (!root) return; // find all DCKWCtextureswitch2 modules on all parts List<DCKWCtextureswitch2> dckWCParts = new List<DCKWCtextureswitch2>(200); foreach (Part p in EditorLogic.fetch.ship.Parts) { dckWCParts.AddRange(p.FindModulesImplementing<DCKWCtextureswitch2>()); } foreach (DCKWCtextureswitch2 dckWCPart in dckWCParts) { dckWCPart.updateSymmetry = false; //FIX symmetry problems because DCK also applies its own logic here // send previous or next command if (next) dckWCPart.nextTextureEvent(); else dckWCPart.previousTextureEvent(); } } void SendEventDCKAA(bool next) //true: next texture, false: previous texture { Part root = EditorLogic.RootPart; if (!root) return; // find all DCKAAtextureswitch2 modules on all parts List<DCKAAtextureswitch2> dckAAParts = new List<DCKAAtextureswitch2>(200); foreach (Part p in EditorLogic.fetch.ship.Parts) { dckAAParts.AddRange(p.FindModulesImplementing<DCKAAtextureswitch2>()); } foreach (DCKAAtextureswitch2 dckAAPart in dckAAParts) { dckAAPart.updateSymmetry = false; //FIX symmetry problems because DCK also applies its own logic here // send previous or next command if (next) dckAAPart.nextTextureEvent(); else dckAAPart.previousTextureEvent(); } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.HttpResponse.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web { sealed public partial class HttpResponse { #region Methods and constructors public void AddCacheDependency(System.Web.Caching.CacheDependency[] dependencies) { } public void AddCacheItemDependencies(string[] cacheKeys) { } public void AddCacheItemDependencies(System.Collections.ArrayList cacheKeys) { } public void AddCacheItemDependency(string cacheKey) { } public void AddFileDependencies(System.Collections.ArrayList filenames) { } public void AddFileDependencies(string[] filenames) { } public void AddFileDependency(string filename) { } public void AddHeader(string name, string value) { } public void AppendCookie(HttpCookie cookie) { } public void AppendHeader(string name, string value) { } public void AppendToLog(string param) { } public string ApplyAppPathModifier(string virtualPath) { return default(string); } public void BinaryWrite(byte[] buffer) { } public void Clear() { } public void ClearContent() { } public void ClearHeaders() { } public void Close() { } public void DisableKernelCache() { } public void End() { } public void Flush() { } public HttpResponse(TextWriter writer) { } public void Pics(string value) { } public void Redirect(string url) { } public void Redirect(string url, bool endResponse) { } public void RedirectPermanent(string url) { } public void RedirectPermanent(string url, bool endResponse) { } public void RedirectToRoute(Object routeValues) { } public void RedirectToRoute(string routeName, Object routeValues) { } public void RedirectToRoute(string routeName) { } public void RedirectToRoute(System.Web.Routing.RouteValueDictionary routeValues) { } public void RedirectToRoute(string routeName, System.Web.Routing.RouteValueDictionary routeValues) { } public void RedirectToRoutePermanent(string routeName, Object routeValues) { } public void RedirectToRoutePermanent(string routeName, System.Web.Routing.RouteValueDictionary routeValues) { } public void RedirectToRoutePermanent(string routeName) { } public void RedirectToRoutePermanent(System.Web.Routing.RouteValueDictionary routeValues) { } public void RedirectToRoutePermanent(Object routeValues) { } public static void RemoveOutputCacheItem(string path, string providerName) { } public static void RemoveOutputCacheItem(string path) { } public void SetCookie(HttpCookie cookie) { } public void TransmitFile(string filename, long offset, long length) { } public void TransmitFile(string filename) { } public void Write(char ch) { } public void Write(char[] buffer, int index, int count) { } public void Write(Object obj) { } public void Write(string s) { } public void WriteFile(IntPtr fileHandle, long offset, long size) { } public void WriteFile(string filename, bool readIntoMemory) { } public void WriteFile(string filename, long offset, long size) { } public void WriteFile(string filename) { } public void WriteSubstitution(HttpResponseSubstitutionCallback callback) { } #endregion #region Properties and indexers public bool Buffer { get { return default(bool); } set { } } public bool BufferOutput { get { return default(bool); } set { } } public HttpCachePolicy Cache { get { return default(HttpCachePolicy); } } public string CacheControl { get { return default(string); } set { } } public string Charset { get { return default(string); } set { } } public Encoding ContentEncoding { get { return default(Encoding); } set { } } public string ContentType { get { return default(string); } set { } } public HttpCookieCollection Cookies { get { return default(HttpCookieCollection); } } public int Expires { get { return default(int); } set { } } public DateTime ExpiresAbsolute { get { return default(DateTime); } set { } } public Stream Filter { get { return default(Stream); } set { } } public Encoding HeaderEncoding { get { return default(Encoding); } set { } } public System.Collections.Specialized.NameValueCollection Headers { get { return default(System.Collections.Specialized.NameValueCollection); } } public bool IsClientConnected { get { return default(bool); } } public bool IsRequestBeingRedirected { get { return default(bool); } } public TextWriter Output { get { return default(TextWriter); } } public Stream OutputStream { get { return default(Stream); } } public string RedirectLocation { get { return default(string); } set { } } public string Status { get { return default(string); } set { } } public int StatusCode { get { return default(int); } set { } } public string StatusDescription { get { return default(string); } set { } } public int SubStatusCode { get { return default(int); } set { } } public bool SuppressContent { get { return default(bool); } set { } } public bool TrySkipIisCustomErrors { get { return default(bool); } set { } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Net.Http.Headers { public class AuthenticationHeaderValue : ICloneable { private string _scheme; private string _parameter; public string Scheme { get { return _scheme; } } // We simplify parameters by just considering them one string. The caller is responsible for correctly parsing // the string. // The reason is that we can't determine the format of parameters. According to Errata 1959 in RFC 2617 // parameters can be "token", "quoted-string", or "#auth-param" where "auth-param" is defined as // "token "=" ( token | quoted-string )". E.g. take the following BASIC example: // Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== // Due to Base64 encoding we have two final "=". The value is neither a token nor a quoted-string, so it must // be an auth-param according to the RFC definition. But that's also incorrect: auth-param means that we // consider the value before the first "=" as "name" and the final "=" as "value". public string Parameter { get { return _parameter; } } public AuthenticationHeaderValue(string scheme) : this(scheme, null) { } public AuthenticationHeaderValue(string scheme, string parameter) { HeaderUtilities.CheckValidToken(scheme, "scheme"); _scheme = scheme; _parameter = parameter; } private AuthenticationHeaderValue(AuthenticationHeaderValue source) { Contract.Requires(source != null); _scheme = source._scheme; _parameter = source._parameter; } private AuthenticationHeaderValue() { } public override string ToString() { if (string.IsNullOrEmpty(_parameter)) { return _scheme; } return _scheme + " " + _parameter; } public override bool Equals(object obj) { AuthenticationHeaderValue other = obj as AuthenticationHeaderValue; if (other == null) { return false; } if (string.IsNullOrEmpty(_parameter) && string.IsNullOrEmpty(other._parameter)) { return (string.Equals(_scheme, other._scheme, StringComparison.OrdinalIgnoreCase)); } else { // Since we can't parse the parameter, we use case-sensitive comparison. return string.Equals(_scheme, other._scheme, StringComparison.OrdinalIgnoreCase) && string.Equals(_parameter, other._parameter, StringComparison.Ordinal); } } public override int GetHashCode() { int result = StringComparer.OrdinalIgnoreCase.GetHashCode(_scheme); if (!string.IsNullOrEmpty(_parameter)) { result = result ^ _parameter.GetHashCode(); } return result; } public static AuthenticationHeaderValue Parse(string input) { int index = 0; return (AuthenticationHeaderValue)GenericHeaderParser.SingleValueAuthenticationParser.ParseValue( input, null, ref index); } public static bool TryParse(string input, out AuthenticationHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (GenericHeaderParser.SingleValueAuthenticationParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (AuthenticationHeaderValue)output; return true; } return false; } internal static int GetAuthenticationLength(string input, int startIndex, out object parsedValue) { Contract.Requires(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Parse the scheme string: <scheme> in '<scheme> <parameter>' int schemeLength = HttpRuleParser.GetTokenLength(input, startIndex); if (schemeLength == 0) { return 0; } AuthenticationHeaderValue result = new AuthenticationHeaderValue(); result._scheme = input.Substring(startIndex, schemeLength); int current = startIndex + schemeLength; int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current); current = current + whitespaceLength; if ((current == input.Length) || (input[current] == ',')) { // If we only have a scheme followed by whitespaces, we're done. parsedValue = result; return current - startIndex; } // We need at least one space between the scheme and parameters. If there are no whitespaces, then we must // have reached the end of the string (i.e. scheme-only string). if (whitespaceLength == 0) { return 0; } // If we get here, we have a <scheme> followed by a whitespace. Now we expect the following: // '<scheme> <blob>[,<name>=<value>]*[, <otherscheme>...]*': <blob> potentially contains one // or more '=' characters, optionally followed by additional name/value pairs, optionally followed by // other schemes. <blob> may be a quoted string. // We look at the value after ',': if it is <token>=<value> then we have a parameter for <scheme>. // If we have either a <token>-only or <token><whitespace><blob> then we have another scheme. int parameterStartIndex = current; int parameterEndIndex = current; if (!TrySkipFirstBlob(input, ref current, ref parameterEndIndex)) { return 0; } if (current < input.Length) { if (!TryGetParametersEndIndex(input, ref current, ref parameterEndIndex)) { return 0; } } result._parameter = input.Substring(parameterStartIndex, parameterEndIndex - parameterStartIndex + 1); parsedValue = result; return current - startIndex; } private static bool TrySkipFirstBlob(string input, ref int current, ref int parameterEndIndex) { // Find the delimiter: Note that <blob> in "<scheme> <blob>" may be a token, quoted string, name/value // pair or a Base64 encoded string. So make sure that we don't consider ',' characters within a quoted // string as delimiter. while ((current < input.Length) && (input[current] != ',')) { if (input[current] == '"') { int quotedStringLength = 0; if (HttpRuleParser.GetQuotedStringLength(input, current, out quotedStringLength) != HttpParseResult.Parsed) { // We have a quote but an invalid quoted-string. return false; } current = current + quotedStringLength; parameterEndIndex = current - 1; // -1 because 'current' points to the char after the final '"' } else { int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current); // We don't want trailing whitespaces to be considered part of the parameter blob. Increment // 'parameterEndIndex' only if we don't have a whitespace. E.g. "Basic AbC= , NTLM" should return // "AbC=" as parameter ignoring the spaces before ','. if (whitespaceLength == 0) { parameterEndIndex = current; current++; } else { current = current + whitespaceLength; } } } return true; } private static bool TryGetParametersEndIndex(string input, ref int parseEndIndex, ref int parameterEndIndex) { Contract.Requires(parseEndIndex < input.Length, "Expected string to have at least 1 char"); Debug.Assert(input[parseEndIndex] == ','); int current = parseEndIndex; do { current++; // skip ',' delimiter bool separatorFound = false; // ignore value returned by GetNextNonEmptyOrWhitespaceIndex() current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out separatorFound); if (current == input.Length) { return true; } // Now we have to determine if after ',' we have a list of <name>=<value> pairs that are part of // the auth scheme parameters OR if we have another auth scheme. Either way, after ',' we expect a // valid token that is either the <name> in a <name>=<value> pair OR <scheme> of another scheme. int tokenLength = HttpRuleParser.GetTokenLength(input, current); if (tokenLength == 0) { return false; } current = current + tokenLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // If we reached the end of the string or the token is followed by anything but '=', then the parsed // token is another scheme name. The string representing parameters ends before the token (e.g. // "Digest a=b, c=d, NTLM": return scheme "Digest" with parameters string "a=b, c=d"). if ((current == input.Length) || (input[current] != '=')) { return true; } current++; // skip '=' delimiter current = current + HttpRuleParser.GetWhitespaceLength(input, current); int valueLength = NameValueHeaderValue.GetValueLength(input, current); // After '<name>=' we expect a valid <value> (either token or quoted string) if (valueLength == 0) { return false; } // Update parameter end index, since we just parsed a valid <name>=<value> pair that is part of the // parameters string. current = current + valueLength; parameterEndIndex = current - 1; // -1 because 'current' already points to the char after <value> current = current + HttpRuleParser.GetWhitespaceLength(input, current); parseEndIndex = current; // this essentially points to parameterEndIndex + whitespaces + next char } while ((current < input.Length) && (input[current] == ',')); return true; } object ICloneable.Clone() { return new AuthenticationHeaderValue(this); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace LitJson { internal enum Condition { InArray, InObject, NotAProperty, Property, Value } internal class WriterContext { public int Count; public bool InArray; public bool InObject; public bool ExpectingValue; public int Padding; } public class JsonWriter { #region Fields private static readonly NumberFormatInfo number_format; private WriterContext context; private Stack<WriterContext> ctx_stack; private bool has_reached_end; private char[] hex_seq; private int indentation; private int indent_value; private StringBuilder inst_string_builder; private bool pretty_print; private bool validate; private bool lower_case_properties; private TextWriter writer; #endregion #region Properties public int IndentValue { get { return indent_value; } set { indentation = (indentation / indent_value) * value; indent_value = value; } } public bool PrettyPrint { get { return pretty_print; } set { pretty_print = value; } } public TextWriter TextWriter { get { return writer; } } public bool Validate { get { return validate; } set { validate = value; } } public bool LowerCaseProperties { get { return lower_case_properties; } set { lower_case_properties = value; } } #endregion #region Constructors static JsonWriter () { number_format = NumberFormatInfo.InvariantInfo; } public JsonWriter () { inst_string_builder = new StringBuilder (); writer = new StringWriter (inst_string_builder); Init (); } public JsonWriter (StringBuilder sb) : this (new StringWriter (sb)) { } public JsonWriter (TextWriter writer) { if (writer == null) throw new ArgumentNullException ("writer"); this.writer = writer; Init (); } #endregion #region Private Methods private void DoValidation (Condition cond) { if (! context.ExpectingValue) context.Count++; if (! validate) return; if (has_reached_end) throw new JsonException ( "A complete JSON symbol has already been written"); switch (cond) { case Condition.InArray: if (! context.InArray) throw new JsonException ( "Can't close an array here"); break; case Condition.InObject: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't close an object here"); break; case Condition.NotAProperty: if (context.InObject && ! context.ExpectingValue) throw new JsonException ( "Expected a property"); break; case Condition.Property: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't add a property here"); break; case Condition.Value: if (! context.InArray && (! context.InObject || ! context.ExpectingValue)) throw new JsonException ( "Can't add a value here"); break; } } private void Init () { has_reached_end = false; hex_seq = new char[4]; indentation = 0; indent_value = 4; pretty_print = false; validate = true; lower_case_properties = false; ctx_stack = new Stack<WriterContext> (); context = new WriterContext (); ctx_stack.Push (context); } private static void IntToHex (int n, char[] hex) { int num; for (int i = 0; i < 4; i++) { num = n % 16; if (num < 10) hex[3 - i] = (char) ('0' + num); else hex[3 - i] = (char) ('A' + (num - 10)); n >>= 4; } } private void Indent () { if (pretty_print) indentation += indent_value; } private void Put (string str) { if (pretty_print && ! context.ExpectingValue) for (int i = 0; i < indentation; i++) writer.Write (' '); writer.Write (str); } private void PutNewline () { PutNewline (true); } private void PutNewline (bool add_comma) { if (add_comma && ! context.ExpectingValue && context.Count > 1) writer.Write (','); if (pretty_print && ! context.ExpectingValue) writer.Write (Environment.NewLine); } private void PutString (string str) { Put (String.Empty); writer.Write ('"'); int n = str.Length; for (int i = 0; i < n; i++) { switch (str[i]) { case '\n': writer.Write ("\\n"); continue; case '\r': writer.Write ("\\r"); continue; case '\t': writer.Write ("\\t"); continue; case '"': case '\\': writer.Write ('\\'); writer.Write (str[i]); continue; case '\f': writer.Write ("\\f"); continue; case '\b': writer.Write ("\\b"); continue; } if ((int) str[i] >= 32 && (int) str[i] <= 126) { writer.Write (str[i]); continue; } // Default, turn into a \uXXXX sequence IntToHex ((int) str[i], hex_seq); writer.Write ("\\u"); writer.Write (hex_seq); } writer.Write ('"'); } private void Unindent () { if (pretty_print) indentation -= indent_value; } #endregion public override string ToString () { if (inst_string_builder == null) return String.Empty; return inst_string_builder.ToString (); } public void Reset () { has_reached_end = false; ctx_stack.Clear (); context = new WriterContext (); ctx_stack.Push (context); if (inst_string_builder != null) inst_string_builder.Remove (0, inst_string_builder.Length); } public void Write (bool boolean) { DoValidation (Condition.Value); PutNewline (); Put (boolean ? "true" : "false"); context.ExpectingValue = false; } public void Write (decimal number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (double number) { DoValidation (Condition.Value); PutNewline (); string str = Convert.ToString (number, number_format); Put (str); if (str.IndexOf ('.') == -1 && str.IndexOf ('E') == -1) writer.Write (".0"); context.ExpectingValue = false; } public void Write (int number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (long number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (string str) { DoValidation (Condition.Value); PutNewline (); if (str == null) Put ("null"); else PutString (str); context.ExpectingValue = false; } public void Write (ulong number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void WriteArrayEnd () { DoValidation (Condition.InArray); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("]"); } public void WriteArrayStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("["); context = new WriterContext (); context.InArray = true; ctx_stack.Push (context); Indent (); } public void WriteObjectEnd () { DoValidation (Condition.InObject); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("}"); } public void WriteObjectStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("{"); context = new WriterContext (); context.InObject = true; ctx_stack.Push (context); Indent (); } public void WritePropertyName (string property_name) { DoValidation (Condition.Property); PutNewline (); string propertyName = (property_name == null || !lower_case_properties) ? property_name : property_name.ToLowerInvariant(); PutString (propertyName); if (pretty_print) { if (propertyName.Length > context.Padding) context.Padding = propertyName.Length; for (int i = context.Padding - propertyName.Length; i >= 0; i--) writer.Write (' '); writer.Write (": "); } else writer.Write (':'); context.ExpectingValue = true; } } }
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 house painting service. /// </summary> public class HousePainter_Core : TypeCore, IHomeAndConstructionBusiness { public HousePainter_Core() { this._TypeId = 133; this._Id = "HousePainter"; this._Schema_Org_Url = "http://schema.org/HousePainter"; string label = ""; GetLabel(out label, "HousePainter", typeof(HousePainter_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,128}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{128,216}; 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); } } } }
// // Json.cs: MonoTouch.Dialog support for creating UIs from Json description files // // Author: // Miguel de Icaza // // See the JSON.md file for documentation // // TODO: Json to load entire view controllers // using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Json; using System.Net; using System.Reflection; using Foundation; using UIKit; using CoreGraphics; using NSAction = global::System.Action; namespace MonoTouch.Dialog { public class JsonElement : RootElement { JsonElement jsonParent; Dictionary<string,Element> map; const int CSIZE = 16; const int SPINNER_TAG = 1000; public string Url; bool loading; public static DateTimeKind DateKind { get; set; } = DateTimeKind.Unspecified; UIActivityIndicatorView StartSpinner (UITableViewCell cell) { var cvb = cell.ContentView.Bounds; var spinner = new UIActivityIndicatorView (new CGRect (cvb.Width-CSIZE/2, (cvb.Height-CSIZE)/2, CSIZE, CSIZE)) { Tag = SPINNER_TAG, ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray, }; cell.ContentView.AddSubview (spinner); spinner.StartAnimating (); cell.Accessory = UITableViewCellAccessory.None; return spinner; } void RemoveSpinner (UITableViewCell cell, UIActivityIndicatorView spinner) { spinner.StopAnimating (); spinner.RemoveFromSuperview (); cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; } public override UITableViewCell GetCell (UITableView tv) { var cell = base.GetCell (tv); if (Url == null) return cell; var spinner = cell.ViewWithTag (SPINNER_TAG) as UIActivityIndicatorView; if (loading){ if (spinner == null) StartSpinner (cell); else if (spinner != null) RemoveSpinner (cell, spinner); } return cell; } #if __UNIFIED__ class ConnectionDelegate : NSUrlConnectionDataDelegate { #else class ConnectionDelegate : NSUrlConnectionDelegate { #endif Action<Stream,NSError> callback; NSMutableData buffer; public ConnectionDelegate (Action<Stream,NSError> callback) { this.callback = callback; buffer = new NSMutableData (); } public override void ReceivedResponse(NSUrlConnection connection, NSUrlResponse response) { buffer.Length = 0; } public override void FailedWithError(NSUrlConnection connection, NSError error) { callback (null, error); } public override void ReceivedData(NSUrlConnection connection, NSData data) { buffer.AppendData (data); } public override void FinishedLoading(NSUrlConnection connection) { callback (buffer.AsStream (), null); } } public override void Selected (DialogViewController dvc, UITableView tableView, NSIndexPath path) { if (Url == null){ base.Selected (dvc, tableView, path); return; } tableView.DeselectRow (path, false); if (loading) return; var cell = GetActiveCell (); var spinner = StartSpinner (cell); loading = true; var request = new NSUrlRequest (new NSUrl (Url), NSUrlRequestCachePolicy.UseProtocolCachePolicy, 60); /*var connection = */new NSUrlConnection (request, new ConnectionDelegate ((data,error) => { loading = false; spinner.StopAnimating (); spinner.RemoveFromSuperview (); if (error == null){ try { var obj = JsonValue.Load (new StreamReader (data)) as JsonObject; if (obj != null){ var root = JsonElement.FromJson (obj); var newDvc = new DialogViewController (root, true) { Autorotate = true }; PrepareDialogViewController (newDvc); dvc.ActivateController (newDvc); return; } } catch (Exception ee){ Console.WriteLine (ee); } } var alertController = UIAlertController.Create ("Error", "Unable to download data", UIAlertControllerStyle.Alert); alertController.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, (obj) => { })); UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController (alertController, true, () => { }); })); } public JsonElement (string caption, string url) : base (caption) { Url = url; } public JsonElement (string caption, int section, int element, string url) : base (caption, section, element) { Url = url; } public JsonElement (string caption, Group group, string url) : base (caption, group) { Url = url; } public static JsonElement FromFile (string file, object arg) { using (var reader = File.OpenRead (file)) return FromJson (JsonObject.Load (reader) as JsonObject, arg); } public static JsonElement FromFile (string file) { return FromFile (file, null); } public static JsonElement FromJson (JsonObject json) { return FromJson (null, json, null); } public static JsonElement FromJson (JsonObject json, object data) { return FromJson (null, json, data); } public static JsonElement FromJson (JsonElement parent, JsonObject json, object data) { if (json == null) return null; var title = GetString (json, "title") ?? ""; var group = GetString (json, "group"); var url = GetString (json, "url"); var radioSelected = GetString (json, "radioselected"); JsonElement root; if (group == null){ if (radioSelected == null) root = new JsonElement (title, url); else root = new JsonElement (title, new RadioGroup (int.Parse (radioSelected)), url); } else { if (radioSelected == null) root = new JsonElement (title, new Group (group), url); else { // It does not seem that we group elements together, notice when I add // the return, and then change my mind, I have to undo *twice* instead of once. root = new JsonElement (title, new RadioGroup (group, int.Parse (radioSelected)), url); } } root.jsonParent = parent; root.LoadSections (GetArray (json, "sections"), data); return root; } void AddMapping (string id, Element element) { if (jsonParent != null){ jsonParent.AddMapping (id, element); return; } if (map == null) map = new Dictionary<string, Element> (); map.Add (id, element); } // // Retrieves the element name "key" // public Element this [string key] { get { if (jsonParent != null) return jsonParent [key]; if (map == null) return null; Element res; if (map.TryGetValue (key, out res)) return res; return null; } } static void Error (string msg) { Console.WriteLine (msg); } static void Error (string fmt, params object [] args) { Error (String.Format (fmt, args)); } static string GetString (JsonValue obj, string key) { if (obj.ContainsKey (key)) if (obj [key].JsonType == JsonType.String) return (string) obj [key]; return null; } static JsonArray GetArray (JsonObject obj, string key) { if (obj.ContainsKey (key)) if (obj [key].JsonType == JsonType.Array) return (JsonArray) obj [key]; return null; } static bool GetBoolean (JsonObject obj, string key) { try { return (bool) obj [key]; } catch { return false; } } void LoadSections (JsonArray array, object data) { if (array == null) return; int n = array.Count; for (int i = 0; i < n; i++){ var jsonSection = array [i]; var header = GetString (jsonSection, "header"); var footer = GetString (jsonSection, "footer"); var id = GetString (jsonSection, "id"); var section = new Section (header, footer); if (jsonSection.ContainsKey ("elements")) LoadSectionElements (section, jsonSection ["elements"] as JsonArray, data); Add (section); if (id != null) AddMapping (id, section); } } static string bundlePath; static string ExpandPath (string path) { if (path != null && path.Length > 1 && path [0] == '~' && path [1] == '/'){ if (bundlePath == null) bundlePath = NSBundle.MainBundle.BundlePath; return Path.Combine (bundlePath, path.Substring (2)); } return path; } static Element LoadBoolean (JsonObject json) { var caption = GetString (json, "caption"); bool bvalue = GetBoolean (json, "value"); var group = GetString (json, "group"); var onImagePath = ExpandPath (GetString (json, "on")); var offImagePath = ExpandPath (GetString (json, "off")); if (onImagePath != null && offImagePath != null){ var onImage = UIImage.FromFile (onImagePath); var offImage = UIImage.FromFile (offImagePath); return new BooleanImageElement (caption, bvalue, onImage, offImage); } else return new BooleanElement (caption, bvalue, group); } static UIKeyboardType ToKeyboardType (string kbdType) { switch (kbdType){ case "numbers": return UIKeyboardType.NumberPad; case "default": return UIKeyboardType.Default; case "ascii": return UIKeyboardType.ASCIICapable; case "numbers-and-punctuation": return UIKeyboardType.NumbersAndPunctuation; case "decimal": return UIKeyboardType.DecimalPad; case "email": return UIKeyboardType.EmailAddress; case "name": return UIKeyboardType.NamePhonePad; case "twitter": return UIKeyboardType.Twitter; case "url": return UIKeyboardType.Url; default: Console.WriteLine ("Unknown keyboard type: {0}, valid values are numbers, default, ascii, numbers-and-punctuation, decimal, email, name, twitter and url", kbdType); break; } return UIKeyboardType.Default; } static UIReturnKeyType ToReturnKeyType (string returnKeyType) { switch (returnKeyType){ case "default": return UIReturnKeyType.Default; case "done": return UIReturnKeyType.Done; case "emergencycall": return UIReturnKeyType.EmergencyCall; case "go": return UIReturnKeyType.Go; case "google": return UIReturnKeyType.Google; case "join": return UIReturnKeyType.Join; case "next": return UIReturnKeyType.Next; case "route": return UIReturnKeyType.Route; case "search": return UIReturnKeyType.Search; case "send": return UIReturnKeyType.Send; case "yahoo": return UIReturnKeyType.Yahoo; default: Console.WriteLine ("Unknown return key type `{0}', valid values are default, done, emergencycall, go, google, join, next, route, search, send and yahoo"); break; } return UIReturnKeyType.Default; } static UITextAutocapitalizationType ToAutocapitalization (string auto) { switch (auto){ case "sentences": return UITextAutocapitalizationType.Sentences; case "none": return UITextAutocapitalizationType.None; case "words": return UITextAutocapitalizationType.Words; case "all": return UITextAutocapitalizationType.AllCharacters; default: Console.WriteLine ("Unknown autocapitalization value: `{0}', allowed values are sentences, none, words and all"); break; } return UITextAutocapitalizationType.Sentences; } static UITextAutocorrectionType ToAutocorrect (JsonValue value) { if (value.JsonType == JsonType.Boolean) return ((bool) value) ? UITextAutocorrectionType.Yes : UITextAutocorrectionType.No; if (value.JsonType == JsonType.String){ var s = ((string) value); if (s == "yes") return UITextAutocorrectionType.Yes; return UITextAutocorrectionType.No; } return UITextAutocorrectionType.Default; } static Element LoadEntry (JsonObject json, bool isPassword) { var caption = GetString (json, "caption"); var value = GetString (json, "value"); var placeholder = GetString (json, "placeholder"); var element = new EntryElement (caption, placeholder, value, isPassword); if (json.ContainsKey ("keyboard")) element.KeyboardType = ToKeyboardType (GetString (json, "keyboard")); if (json.ContainsKey ("return-key")) element.ReturnKeyType = ToReturnKeyType (GetString (json, "return-key")); if (json.ContainsKey ("capitalization")) element.AutocapitalizationType = ToAutocapitalization (GetString (json, "capitalization")); if (json.ContainsKey ("autocorrect")) element.AutocorrectionType = ToAutocorrect (json ["autocorrect"]); return element; } static UITableViewCellAccessory ToAccessory (string accesory) { switch (accesory){ case "checkmark": return UITableViewCellAccessory.Checkmark; case "detail-disclosure": return UITableViewCellAccessory.DetailDisclosureButton; case "disclosure-indicator": return UITableViewCellAccessory.DisclosureIndicator; } return UITableViewCellAccessory.None; } static int FromHex (char c) { if (c >= '0' && c <= '9') return c-'0'; if (c >= 'a' && c <= 'f') return c-'a'+10; if (c >= 'A' && c <= 'F') return c-'A'+10; Console.WriteLine ("Unexpected `{0}' in hex value for color", c); return 0; } static void ColorError (string text) { Console.WriteLine ("Unknown color specification {0}, expecting #rgb, #rgba, #rrggbb or #rrggbbaa formats", text); } static UIColor ParseColor (string text) { int tl = text.Length; if (tl > 1 && text [0] == '#'){ int r, g, b, a; if (tl == 4 || tl == 5){ r = FromHex (text [1]); g = FromHex (text [2]); b = FromHex (text [3]); a = tl == 5 ? FromHex (text [4]) : 15; r = r << 4 | r; g = g << 4 | g; b = b << 4 | b; a = a << 4 | a; } else if (tl == 7 || tl == 9){ r = FromHex (text [1]) << 4 | FromHex (text [2]); g = FromHex (text [3]) << 4 | FromHex (text [4]); b = FromHex (text [5]) << 4 | FromHex (text [6]); a = tl == 9 ? FromHex (text [7]) << 4 | FromHex (text [8]) : 255; } else { ColorError (text); return UIColor.Black; } return UIColor.FromRGBA (r, g, b, a); } ColorError (text); return UIColor.Black; } static UILineBreakMode ToLinebreakMode (string mode) { switch (mode){ case "character-wrap": return UILineBreakMode.CharacterWrap; case "clip": return UILineBreakMode.Clip; case "head-truncation": return UILineBreakMode.HeadTruncation; case "middle-truncation": return UILineBreakMode.MiddleTruncation; case "tail-truncation": return UILineBreakMode.TailTruncation; case "word-wrap": return UILineBreakMode.WordWrap; default: Console.WriteLine ("Unexpeted linebreak mode `{0}', valid values include: character-wrap, clip, head-truncation, middle-truncation, tail-truncation and word-wrap", mode); return UILineBreakMode.Clip; } } // Parses a font in the format: // Name[-SIZE] // if -SIZE is omitted, then the value is SystemFontSize // static UIFont ToFont (string kvalue) { int q = kvalue.LastIndexOf ("-"); string fname = kvalue; nfloat fsize = 0; if (q != -1) { nfloat.TryParse (kvalue.Substring (q+1), out fsize); fname = kvalue.Substring (0, q); } if (fsize <= 0) { #if __TVOS__ fsize = UIFont.SystemFontOfSize (12).PointSize; #else fsize = UIFont.SystemFontSize; #endif // __TVOS__ } var f = UIFont.FromName (fname, fsize); if (f == null) return UIFont.SystemFontOfSize (12); return f; } static UITableViewCellStyle ToCellStyle (string style) { switch (style){ case "default": return UITableViewCellStyle.Default; case "subtitle": return UITableViewCellStyle.Subtitle; case "value1": return UITableViewCellStyle.Value1; case "value2": return UITableViewCellStyle.Value2; default: Console.WriteLine ("unknown cell style `{0}', valid values are default, subtitle, value1 and value2", style); break; } return UITableViewCellStyle.Default; } static UITextAlignment ToAlignment (string align) { switch (align){ case "center": return UITextAlignment.Center; case "left": return UITextAlignment.Left; case "right": return UITextAlignment.Right; default: Console.WriteLine ("Unknown alignment `{0}'. valid values are left, center, right", align); return UITextAlignment.Left; } } // // Creates one of the various StringElement classes, based on the // properties set. It tries to load the most memory efficient one // StringElement, if not, it fallsback to MultilineStringElement or // StyledStringElement // static Element LoadString (JsonObject json, object data) { string value = null; string caption = value; string background = null; NSAction ontap = null; NSAction onaccessorytap = null; int? lines = null; UITableViewCellAccessory? accessory = null; UILineBreakMode? linebreakmode = null; UITextAlignment? alignment = null; UIColor textcolor = null, detailcolor = null; UIFont font = null; UIFont detailfont = null; UITableViewCellStyle style = UITableViewCellStyle.Value1; foreach (var kv in json){ string kvalue = (string) kv.Value; switch (kv.Key){ case "caption": caption = kvalue; break; case "value": value = kvalue; break; case "background": background = kvalue; break; case "style": style = ToCellStyle (kvalue); break; case "ontap": case "onaccessorytap": string sontap = kvalue; int p = sontap.LastIndexOf ('.'); if (p == -1) break; NSAction d = delegate { string cname = sontap.Substring (0, p); string mname = sontap.Substring (p+1); foreach (var a in AppDomain.CurrentDomain.GetAssemblies ()){ Type type = a.GetType (cname); if (type != null){ var mi = type.GetMethod (mname, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (mi != null) mi.Invoke (null, new object [] { data }); break; } } }; if (kv.Key == "ontap") ontap = d; else onaccessorytap = d; break; case "lines": int res; if (int.TryParse (kvalue, out res)) lines = res; break; case "accessory": accessory = ToAccessory (kvalue); break; case "textcolor": textcolor = ParseColor (kvalue); break; case "linebreak": linebreakmode = ToLinebreakMode (kvalue); break; case "font": font = ToFont (kvalue); break; case "subtitle": value = kvalue; style = UITableViewCellStyle.Subtitle; break; case "detailfont": detailfont = ToFont (kvalue); break; case "alignment": alignment = ToAlignment (kvalue); break; case "detailcolor": detailcolor = ParseColor (kvalue); break; case "type": break; default: Console.WriteLine ("Unknown attribute: '{0}'", kv.Key); break; } } if (caption == null) caption = ""; if (font != null || style != UITableViewCellStyle.Value1 || detailfont != null || linebreakmode.HasValue || textcolor != null || accessory.HasValue || onaccessorytap != null || background != null || detailcolor != null){ StyledStringElement styled; if (lines.HasValue){ styled = new StyledMultilineElement (caption, value, style); styled.Lines = lines.Value; } else { styled = new StyledStringElement (caption, value, style); } if (ontap != null) styled.Tapped += ontap; if (onaccessorytap != null) styled.AccessoryTapped += onaccessorytap; if (font != null) styled.Font = font; if (detailfont != null) styled.SubtitleFont = detailfont; if (detailcolor != null) styled.DetailColor = detailcolor; if (textcolor != null) styled.TextColor = textcolor; if (accessory.HasValue) styled.Accessory = accessory.Value; if (linebreakmode.HasValue) styled.LineBreakMode = linebreakmode.Value; if (background != null){ if (background.Length > 1 && background [0] == '#') styled.BackgroundColor = ParseColor (background); else styled.BackgroundUri = new Uri (background); } if (alignment.HasValue) styled.Alignment = alignment.Value; return styled; } else { StringElement se; if (lines == 0) se = new MultilineElement (caption, value); else se = new StringElement (caption, value); if (alignment.HasValue) se.Alignment = alignment.Value; if (ontap != null) se.Tapped += ontap; return se; } } static Element LoadRadio (JsonObject json, object data) { var caption = GetString (json, "caption"); var group = GetString (json, "group"); if (group != null) return new RadioElement (caption, group); else return new RadioElement (caption); } static Element LoadCheckbox (JsonObject json, object data) { var caption = GetString (json, "caption"); var group = GetString (json, "group"); var value = GetBoolean (json, "value"); return new CheckboxElement (caption, value, group); } static DateTime GetDateWithKind (DateTime dt, DateTimeKind parsedKind) { // First we check if the given date has a specified Kind, we just return the same date if found. if (dt.Kind != DateTimeKind.Unspecified) return dt; // If not found then we check if we were able to parse a DateTimeKind from the parsedKind param else if (parsedKind != DateTimeKind.Unspecified) return DateTime.SpecifyKind (dt, parsedKind); // If no DateTimeKind from the parsedKind param was found then we check our global property from JsonElement.DateKind else if (JsonElement.DateKind != DateTimeKind.Unspecified) return DateTime.SpecifyKind (dt, JsonElement.DateKind); // If none of the above is found then we just defaut to local else return DateTime.SpecifyKind (dt, DateTimeKind.Local); } static Element LoadDateTime (JsonObject json, string type) { var caption = GetString (json, "caption"); var date = GetString (json, "value"); var kind = GetString (json, "kind"); DateTime datetime; DateTimeKind dateKind; if (!DateTime.TryParse (date, out datetime)) return null; if (kind != null) { switch (kind.ToLowerInvariant ()) { case "local": dateKind = DateTimeKind.Local; break; case "utc": dateKind = DateTimeKind.Utc; break; default: dateKind = DateTimeKind.Unspecified; break; } } else dateKind = DateTimeKind.Unspecified; datetime = GetDateWithKind (datetime, dateKind); switch (type){ case "date": return new DateElement (caption, datetime); case "time": return new TimeElement (caption, datetime); case "datetime": return new DateTimeElement (caption, datetime); default: return null; } } static Element LoadHtmlElement (JsonObject json) { var caption = GetString (json, "caption"); var url = GetString (json, "url"); return new HtmlElement (caption, url); } void LoadSectionElements (Section section, JsonArray array, object data) { if (array == null) return; for (int i = 0; i < array.Count; i++){ Element element = null; try { var json = array [i] as JsonObject; if (json == null) continue; var type = GetString (json, "type"); switch (type){ case "bool": case "boolean": element = LoadBoolean (json); break; case "entry": case "password": element = LoadEntry (json, type == "password"); break; case "string": element = LoadString (json, data); break; case "root": element = FromJson (this, json, data); break; case "radio": element = LoadRadio (json, data); break; case "checkbox": element = LoadCheckbox (json, data); break; case "datetime": case "date": case "time": element = LoadDateTime (json, type); break; case "html": element = LoadHtmlElement (json); break; default: Error ("json element at {0} contain an unknown type `{1}', json {2}", i, type, json); break; } if (element != null){ var id = GetString (json, "id"); if (id != null) AddMapping (id, element); } } catch (Exception e) { Console.WriteLine ("Error processing Json {0}, exception {1}", array, e); } if (element != null) section.Add (element); } } } }
using NUnit.Framework; using Revolver.Core; using Sitecore; using Sitecore.Configuration; using Sitecore.Data.Items; using Sitecore.Resources.Media; using System.IO; using Cmd = Revolver.Core.Commands; namespace Revolver.Test { [TestFixture] [Category("CopyItem")] public class CopyItem : BaseCommandTest { TemplateItem _template = null; Item _singleTestRoot = null; Item _masterTestRoot = null; Item _mediaTestRoot = null; [TestFixtureSetUp] public void TestFixtureSetUp() { Sitecore.Context.IsUnitTesting = true; Sitecore.Context.SkipSecurityInUnitTests = true; _context.CurrentDatabase = Sitecore.Configuration.Factory.GetDatabase("web"); _template = _context.CurrentDatabase.Templates[Constants.Paths.DocTemplate]; var masterDB = Sitecore.Configuration.Factory.GetDatabase("master"); var masterContent = masterDB.GetItem(ItemIDs.ContentRoot); InitContent(); _masterTestRoot = masterContent.Add("test root-" + DateUtil.IsoNow, _template); var mediaFolderTemplate = masterDB.Templates["system/media/media folder"]; _mediaTestRoot = masterDB.GetItem("/sitecore/media library/images").Add("test-" + DateUtil.IsoNow, mediaFolderTemplate); } [TestFixtureTearDown] public void TestFixtureTearDown() { if (_masterTestRoot != null) _masterTestRoot.Delete(); if (_mediaTestRoot != null) _mediaTestRoot.Delete(); } [TearDown] public void TearDown() { if (_singleTestRoot != null) _singleTestRoot.Delete(); _masterTestRoot.DeleteChildren(); } [SetUp] public void SetUp() { _context.CurrentDatabase = Sitecore.Configuration.Factory.GetDatabase("web"); _singleTestRoot = _testRoot.Add("single test root" + DateUtil.IsoNow, _template); } [Test] public void NoArguments() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var res = cmd.Run(); Assert.AreEqual(CommandStatus.Failure, res.Status); } [Test] public void ContextToExistingPath() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var sourceItem = _singleTestRoot.Add("source", _template); var targetItem = _singleTestRoot.Add("target", _template); _context.CurrentItem = sourceItem; cmd.TargetPath = targetItem.Paths.FullPath; var res = cmd.Run(); targetItem.Reload(); Assert.AreEqual(CommandStatus.Success, res.Status); Assert.AreEqual(1, targetItem.GetChildren().Count); Assert.AreEqual(sourceItem.Name, targetItem.Children[0].Name); } [Test] public void ContextToSelf() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var sourceItem = _singleTestRoot.Add("source", _template); _context.CurrentItem = sourceItem; cmd.TargetPath = "."; var res = cmd.Run(); Assert.AreEqual(CommandStatus.Success, res.Status); Assert.AreEqual(1, sourceItem.GetChildren().Count); Assert.AreEqual(sourceItem.Name, sourceItem.Children[0].Name); } [Test] public void ContextToNewPath() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var sourceItem = _singleTestRoot.Add("source", _template); var targetItem = _singleTestRoot.Add("target", _template); _context.CurrentItem = sourceItem; cmd.TargetPath = targetItem.Paths.FullPath + "/newpath"; var res = cmd.Run(); targetItem.Reload(); Assert.AreEqual(CommandStatus.Success, res.Status); Assert.AreEqual(1, targetItem.GetChildren().Count); Assert.AreEqual("newpath", targetItem.Children[0].Name); } [Test] public void ContextToNewPathRecursive() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var sourceItem = _singleTestRoot.Add("source", _template); var sourceChildItem = sourceItem.Add("child1", _template); var targetItem = _singleTestRoot.Add("target", _template); _context.CurrentItem = sourceItem; cmd.TargetPath = targetItem.Paths.FullPath + "/newpath"; cmd.Recursive = true; var res = cmd.Run(); targetItem.Reload(); Assert.AreEqual(CommandStatus.Success, res.Status); Assert.AreEqual(1, targetItem.GetChildren().Count); Assert.AreEqual("newpath", targetItem.Children[0].Name); Assert.AreEqual(1, targetItem.Children[0].GetChildren().Count); Assert.AreEqual(sourceChildItem.Name, targetItem.Children[0].Children[0].Name); } [Test] public void ContextToNewPathFromTreeNonRecursive() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var sourceItem = _singleTestRoot.Add("source", _template); var sourceChildItem = sourceItem.Add("child1", _template); var targetItem = _singleTestRoot.Add("target", _template); _context.CurrentItem = sourceItem; cmd.TargetPath = targetItem.Paths.FullPath + "/newpath"; var res = cmd.Run(); targetItem.Reload(); Assert.AreEqual(CommandStatus.Success, res.Status); Assert.AreEqual(1, targetItem.GetChildren().Count); Assert.AreEqual("newpath", targetItem.Children[0].Name); Assert.AreEqual(0, targetItem.Children[0].GetChildren().Count); } [Test] public void ContextToDBSameID() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var sourceItem = _singleTestRoot.Add("source", _template); _context.CurrentItem = sourceItem; cmd.TargetPath = "/master/sitecore/content/" + _masterTestRoot.Name; var res = cmd.Run(); _masterTestRoot.Reload(); var masterCopy = _masterTestRoot.Axes.GetChild(sourceItem.ID); Assert.AreEqual(CommandStatus.Success, res.Status); Assert.IsNotNull(masterCopy); Assert.AreEqual(sourceItem.ID, masterCopy.ID); } [Test] public void ContextToDBDifferentID() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var sourceItem = _singleTestRoot.Add("source", _template); _context.CurrentItem = sourceItem; cmd.TargetPath = "/master/sitecore/content/" + _masterTestRoot.Name; cmd.NewId = true; var res = cmd.Run(); _masterTestRoot.Reload(); var masterCopy = _masterTestRoot.Axes.GetChild(sourceItem.Name); Assert.AreEqual(CommandStatus.Success, res.Status); Assert.IsNotNull(masterCopy); Assert.AreNotEqual(sourceItem.ID, masterCopy.ID); } [Test] public void DifferentItemToExistingPathRelative() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var sourceItem = _singleTestRoot.Add("source", _template); var targetItem = _singleTestRoot.Add("target", _template); _context.CurrentItem = _singleTestRoot.Parent; cmd.SourcePath = _singleTestRoot.Name + "/" + sourceItem.Name; cmd.TargetPath = _singleTestRoot.Name + "/" + targetItem.Name; var res = cmd.Run(); targetItem.Reload(); Assert.AreEqual(CommandStatus.Success, res.Status); Assert.AreEqual(1, targetItem.GetChildren().Count); Assert.AreEqual(sourceItem.Name, targetItem.Children[0].Name); Assert.AreEqual(0, targetItem.Children[0].GetChildren().Count); } [Test] public void DifferentItemToExistingPathAbsolute() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var sourceItem = _singleTestRoot.Add("source", _template); var targetItem = _singleTestRoot.Add("target", _template); _context.CurrentItem = _singleTestRoot.Parent; cmd.SourcePath = _singleTestRoot.Name + "/" + sourceItem.Name; cmd.TargetPath = targetItem.Paths.FullPath; var res = cmd.Run(); targetItem.Reload(); Assert.AreEqual(CommandStatus.Success, res.Status); Assert.AreEqual(1, targetItem.GetChildren().Count); Assert.AreEqual(sourceItem.Name, targetItem.Children[0].Name); Assert.AreEqual(0, targetItem.Children[0].GetChildren().Count); } [Test] public void InvalidSource() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var targetItem = _singleTestRoot.Add("target", _template); _context.CurrentItem = _singleTestRoot.Parent; cmd.SourcePath = "/sitecore/content/thia/path/doesnt/exist"; cmd.TargetPath = targetItem.Paths.FullPath; var res = cmd.Run(); Assert.AreEqual(CommandStatus.Failure, res.Status); } [Test] public void InvalidTarget() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var sourceItem = _singleTestRoot.Add("source", _template); _context.CurrentItem = _singleTestRoot.Parent; cmd.SourcePath = _singleTestRoot.Name + "/" + sourceItem.Name; cmd.TargetPath = "/sitecore/content/thia/path/doesnt/exist"; var res = cmd.Run(); Assert.AreEqual(CommandStatus.Failure, res.Status); } [Test] public void DisallowCopyToLanguage() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); cmd.TargetPath = ":de"; var result = cmd.Run(); Assert.That(result.Status, Is.EqualTo(CommandStatus.Failure)); } [Test] public void DisallowCopyToVersion() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); cmd.TargetPath = "::2"; var result = cmd.Run(); Assert.That(result.Status, Is.EqualTo(CommandStatus.Failure)); } [Test] public void CopyMedia() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var image = AddTestImageToMaster(); var targetItem = image.InnerItem.Add("target", _template); _context.CurrentItem = image; cmd.TargetPath = targetItem.Paths.FullPath + "/newpath"; var res = cmd.Run(); targetItem.Reload(); Assert.AreEqual(CommandStatus.Success, res.Status); Assert.AreEqual(1, targetItem.GetChildren().Count); Assert.AreEqual("newpath", targetItem.Children[0].Name); Stream stream = ((MediaItem)targetItem.Children[0]).GetMediaStream(); Assert.IsNotNull(stream); Assert.Greater(stream.Length, 0); } [Test] public void CopyMediaRecursive() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var mediaFolder = CreateImageFoldersInMaster(); var targetItem = _mediaTestRoot.Add("target-" + DateUtil.IsoNow, _template); _context.CurrentItem = mediaFolder; cmd.TargetPath = targetItem.Paths.FullPath + "/newpath"; cmd.Recursive = true; var res = cmd.Run(); targetItem.Reload(); Assert.AreEqual(CommandStatus.Success, res.Status); Assert.AreEqual(1, targetItem.GetChildren().Count); Assert.AreEqual("newpath", targetItem.Children[0].Name); Assert.AreEqual(2, targetItem.Children[0].GetChildren().Count); var stream = ((MediaItem)targetItem.Children[0].Children[0]).GetMediaStream(); Assert.IsNotNull(stream); Assert.Greater(stream.Length, 0); var stream2 = ((MediaItem)targetItem.Children[0].Children[1]).GetMediaStream(); Assert.IsNotNull(stream2); Assert.Greater(stream2.Length, 0); } [Test] public void CopyMediaToDifferentDB() { var cmd = new Cmd.CopyItem(); InitCommand(cmd); var targetPath = "/sitecore/media library/images/test-image"; var image = AddTestImageToMaster(); _context.CurrentItem = image; cmd.TargetPath = "/web" + targetPath; var res = cmd.Run(); Assert.AreEqual(CommandStatus.Success, res.Status); var webImage = Factory.GetDatabase("web").GetItem(targetPath); Assert.IsNotNull(webImage); Stream stream = ((MediaItem)webImage).GetMediaStream(); Assert.IsNotNull(stream); Assert.Greater(stream.Length, 0); } private MediaItem AddTestImageToMaster() { return AddTestImageToMaster(_mediaTestRoot.Paths.FullPath + "/sometest-" + DateUtil.IsoNow); } private MediaItem AddTestImageToMaster(string parent) { var masterDatabase = Sitecore.Configuration.Factory.GetDatabase("master"); var options = new MediaCreatorOptions { Database = masterDatabase, Destination = parent }; return MediaManager.Creator.CreateFromFile("~/TestResources/visual_list.png", options); } private Item CreateImageFoldersInMaster() { var masterDatabase = Sitecore.Configuration.Factory.GetDatabase("master"); var folderTemplate = masterDatabase.Templates["system/media/media folder"]; var folder = _mediaTestRoot.Add("test folder-" + DateUtil.IsoNow, folderTemplate); var image1 = AddTestImageToMaster(folder.Paths.FullPath + "/image1"); var image2 = AddTestImageToMaster(folder.Paths.FullPath + "/image2"); return folder; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.MenuItemBinding.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls { sealed public partial class MenuItemBinding : System.Web.UI.IStateManager, ICloneable, System.Web.UI.IDataSourceViewSchemaAccessor { #region Methods and constructors public MenuItemBinding() { } Object System.ICloneable.Clone() { return default(Object); } void System.Web.UI.IStateManager.LoadViewState(Object state) { } Object System.Web.UI.IStateManager.SaveViewState() { return default(Object); } void System.Web.UI.IStateManager.TrackViewState() { } public override string ToString() { return default(string); } #endregion #region Properties and indexers public string DataMember { get { return default(string); } set { } } public int Depth { get { return default(int); } set { } } public bool Enabled { get { return default(bool); } set { } } public string EnabledField { get { return default(string); } set { } } public string FormatString { get { return default(string); } set { } } public string ImageUrl { get { return default(string); } set { } } public string ImageUrlField { get { return default(string); } set { } } public string NavigateUrl { get { return default(string); } set { } } public string NavigateUrlField { get { return default(string); } set { } } public string PopOutImageUrl { get { return default(string); } set { } } public string PopOutImageUrlField { get { return default(string); } set { } } public bool Selectable { get { return default(bool); } set { } } public string SelectableField { get { return default(string); } set { } } public string SeparatorImageUrl { get { return default(string); } set { } } public string SeparatorImageUrlField { get { return default(string); } set { } } Object System.Web.UI.IDataSourceViewSchemaAccessor.DataSourceViewSchema { get { return default(Object); } set { } } bool System.Web.UI.IStateManager.IsTrackingViewState { get { return default(bool); } } public string Target { get { return default(string); } set { } } public string TargetField { get { return default(string); } set { } } public string Text { get { return default(string); } set { } } public string TextField { get { return default(string); } set { } } public string ToolTip { get { return default(string); } set { } } public string ToolTipField { get { return default(string); } set { } } public string Value { get { return default(string); } set { } } public string ValueField { get { return default(string); } set { } } #endregion } }
// 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.Contracts; namespace Microsoft.Cci { using Microsoft.Cci.ILGeneratorImplementation; /// <summary> /// A metadata (IL) level represetation of the body of a method or of a property/event accessor. /// </summary> public class ILGeneratorMethodBody : IMethodBody { /// <summary> /// Allocates an object that is the metadata (IL) level represetation of the body of a method or of a property/event accessor. /// </summary> /// <param name="generator">An object that provides a way to construct the information needed by a method body. Construction should /// be completed by the time the generator is passed to this constructor. The generator is not referenced by the resulting method body.</param> /// <param name="localsAreZeroed">True if the locals are initialized by zeroeing the stack upon method entry.</param> /// <param name="maxStack">The maximum number of elements on the evaluation stack during the execution of the method.</param> /// <param name="methodDefinition">The definition of the method whose body this is. /// If this is the body of an event or property accessor, this will hold the corresponding adder/remover/setter or getter method.</param> /// <param name="localVariables"></param> /// <param name="privateHelperTypes">Any types that are implicitly defined in order to implement the body semantics. /// In case of AST to instructions conversion this lists the types produced. /// In case of instructions to AST decompilation this should ideally be list of all types /// which are local to method.</param> public ILGeneratorMethodBody(ILGenerator generator, bool localsAreZeroed, ushort maxStack, IMethodDefinition methodDefinition, IEnumerable<ILocalDefinition> localVariables, IEnumerable<ITypeDefinition> privateHelperTypes) { Contract.Requires(generator != null); Contract.Requires(methodDefinition != null); Contract.Requires(localVariables != null); Contract.Requires(privateHelperTypes != null); this.localsAreZeroed = localsAreZeroed; this.operationExceptionInformation = generator.GetOperationExceptionInformation(); this.operations = generator.GetOperations(); this.privateHelperTypes = privateHelperTypes; this.generatorIteratorScopes = generator.GetIteratorScopes(); this.generatorLocalScopes = generator.GetLocalScopes(); this.localVariables = localVariables; this.maxStack = maxStack; this.methodDefinition = methodDefinition; this.size = generator.CurrentOffset; this.synchronizationInformation = generator.GetSynchronizationInformation(); } /// <summary> /// Calls visitor.Visit(IMethodBody). /// </summary> public void Dispatch(IMetadataVisitor visitor) { visitor.Visit(this); } readonly IEnumerable<ILocalScope>/*?*/ generatorIteratorScopes; readonly IEnumerable<ILGeneratorScope> generatorLocalScopes; readonly ISynchronizationInformation/*?*/ synchronizationInformation; /// <summary> /// Returns a block scope associated with each local variable in the iterator for which this is the generator for its MoveNext method. /// May return null. /// </summary> /// <remarks>The PDB file model seems to be that scopes are duplicated if necessary so that there is a separate scope for each /// local variable in the original iterator and the mapping from local to scope is done by position.</remarks> public IEnumerable<ILocalScope>/*?*/ GetIteratorScopes() { return this.generatorIteratorScopes; } /// <summary> /// Returns zero or more local (block) scopes into which the CLR IL operations of this method body is organized. /// </summary> public IEnumerable<ILocalScope> GetLocalScopes() { foreach (var generatorScope in this.generatorLocalScopes) { if (generatorScope.locals.Count > 0) yield return generatorScope; } } /// <summary> /// Returns zero or more namespace scopes into which the namespace type containing the given method body has been nested. /// These scopes determine how simple names are looked up inside the method body. There is a separate scope for each dotted /// component in the namespace type name. For istance namespace type x.y.z will have two namespace scopes, the first is for the x and the second /// is for the y. /// </summary> public IEnumerable<INamespaceScope> GetNamespaceScopes() { foreach (var generatorScope in this.generatorLocalScopes) { if (generatorScope.usedNamespaces.Count > 0) yield return generatorScope; } } /// <summary> /// Returns an object that describes where synchronization points occur in the IL operations of the "MoveNext" method of /// the state class of an async method. Returns null otherwise. /// </summary> public ISynchronizationInformation/*?*/ GetSynchronizationInformation() { return this.synchronizationInformation; } /// <summary> /// A list exception data within the method body IL. /// </summary> public IEnumerable<IOperationExceptionInformation> OperationExceptionInformation { [ContractVerification(false)] get { return this.operationExceptionInformation; } } readonly IEnumerable<IOperationExceptionInformation> operationExceptionInformation; /// <summary> /// True if the locals are initialized by zeroeing the stack upon method entry. /// </summary> public bool LocalsAreZeroed { get { return this.localsAreZeroed; } } readonly bool localsAreZeroed; /// <summary> /// The local variables of the method. /// </summary> public IEnumerable<ILocalDefinition> LocalVariables { [ContractVerification(false)] get { return this.localVariables; } } readonly IEnumerable<ILocalDefinition> localVariables; /// <summary> /// The definition of the method whose body this is. /// If this is the body of an event or property accessor, this will hold the corresponding adder/remover/setter or getter method. /// </summary> public IMethodDefinition MethodDefinition { get { return this.methodDefinition; } } readonly IMethodDefinition methodDefinition; /// <summary> /// A list CLR IL operations that implement this method body. /// </summary> public IEnumerable<IOperation> Operations { [ContractVerification(false)] get { return this.operations; } } readonly IEnumerable<IOperation> operations; /// <summary> /// The maximum number of elements on the evaluation stack during the execution of the method. /// </summary> public ushort MaxStack { get { return this.maxStack; } } readonly ushort maxStack; /// <summary> /// Any types that are implicitly defined in order to implement the body semantics. /// In case of AST to instructions conversion this lists the types produced. /// In case of instructions to AST decompilation this should ideally be list of all types /// which are local to method. /// </summary> public IEnumerable<ITypeDefinition> PrivateHelperTypes { [ContractVerification(false)] get { return this.privateHelperTypes; } } readonly IEnumerable<ITypeDefinition> privateHelperTypes; /// <summary> /// The size in bytes of the method body when serialized. /// </summary> public uint Size { get { return this.size; } } readonly uint size; } /// <summary> /// An object that can provide information about the local scopes of a method and that can map ILocation objects /// to IPrimarySourceLocation objects. /// </summary> public class ILGeneratorSourceInformationProvider : ILocalScopeProvider, ISourceLocationProvider { /// <summary> /// Returns zero or more local (block) scopes, each defining an IL range in which an iterator local is defined. /// The scopes are returned by the MoveNext method of the object returned by the iterator method. /// The index of the scope corresponds to the index of the local. Specifically local scope i corresponds /// to the local stored in field &lt;localName&gt;x_i of the class used to store the local values in between /// calls to MoveNext. /// </summary> public virtual IEnumerable<ILocalScope> GetIteratorScopes(IMethodBody methodBody) { return Enumerable<ILocalScope>.Empty; } /// <summary> /// Returns zero or more local (block) scopes into which the CLR IL operations in the given method body is organized. /// </summary> public virtual IEnumerable<ILocalScope> GetLocalScopes(IMethodBody methodBody) { var ilGeneratorMethodBody = methodBody as ILGeneratorMethodBody; if (ilGeneratorMethodBody == null) return Enumerable<ILocalScope>.Empty; return ilGeneratorMethodBody.GetLocalScopes(); } /// <summary> /// Returns zero or more namespace scopes into which the namespace type containing the given method body has been nested. /// These scopes determine how simple names are looked up inside the method body. There is a separate scope for each dotted /// component in the namespace type name. For istance namespace type x.y.z will have two namespace scopes, the first is for the x and the second /// is for the y. /// </summary> public virtual IEnumerable<INamespaceScope> GetNamespaceScopes(IMethodBody methodBody) { var ilGeneratorMethodBody = methodBody as ILGeneratorMethodBody; if (ilGeneratorMethodBody == null) return Enumerable<INamespaceScope>.Empty; return ilGeneratorMethodBody.GetNamespaceScopes(); } /// <summary> /// Returns zero or more local constant definitions that are local to the given scope. /// </summary> public virtual IEnumerable<ILocalDefinition> GetConstantsInScope(ILocalScope scope) { var ilGeneratorScope = scope as ILGeneratorScope; if (ilGeneratorScope == null) return Enumerable<ILocalDefinition>.Empty; return ilGeneratorScope.Constants; } /// <summary> /// Returns zero or more local variable definitions that are local to the given scope. /// </summary> public virtual IEnumerable<ILocalDefinition> GetVariablesInScope(ILocalScope scope) { var ilGeneratorScope = scope as ILGeneratorScope; if (ilGeneratorScope == null) return Enumerable<ILocalDefinition>.Empty; return ilGeneratorScope.Locals; } /// <summary> /// Returns true if the method body is an iterator. /// </summary> public virtual bool IsIterator(IMethodBody methodBody) { return false; } /// <summary> /// If the given method body is the "MoveNext" method of the state class of an asynchronous method, the returned /// object describes where synchronization points occur in the IL operations of the "MoveNext" method. Otherwise /// the result is null. /// </summary> public ISynchronizationInformation/*?*/ GetSynchronizationInformation(IMethodBody methodBody) { return null; } /// <summary> /// Return zero or more locations in primary source documents that correspond to one or more of the given derived (non primary) document locations. /// </summary> public virtual IEnumerable<IPrimarySourceLocation> GetPrimarySourceLocationsFor(IEnumerable<ILocation> locations) { foreach (var location in locations) { IPrimarySourceLocation psloc = location as IPrimarySourceLocation; if (psloc != null) yield return psloc; } } /// <summary> /// Return zero or more locations in primary source documents that correspond to the given derived (non primary) document location. /// </summary> public virtual IEnumerable<IPrimarySourceLocation> GetPrimarySourceLocationsFor(ILocation location) { IPrimarySourceLocation psloc = location as IPrimarySourceLocation; if (psloc != null) yield return psloc; } /// <summary> /// Return zero or more locations in primary source documents that correspond to the definition of the given local. /// </summary> public virtual IEnumerable<IPrimarySourceLocation> GetPrimarySourceLocationsForDefinitionOf(ILocalDefinition localDefinition) { return Enumerable<IPrimarySourceLocation>.Empty; } /// <summary> /// Returns the source name of the given local definition, if this is available. /// Otherwise returns the value of the Name property and sets isCompilerGenerated to true. /// </summary> public virtual string GetSourceNameFor(ILocalDefinition localDefinition, out bool isCompilerGenerated) { isCompilerGenerated = false; var generatorLocal = localDefinition as GeneratorLocal; if (generatorLocal != null) isCompilerGenerated = generatorLocal.IsCompilerGenerated; return localDefinition.Name.Value; } } }
#region File Description //----------------------------------------------------------------------------- // Character.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Diagnostics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; #endregion namespace RolePlayingGameData { /// <summary> /// A character in the game world. /// </summary> [DebuggerDisplay("Name = {name}")] public abstract class Character : WorldObject { #region Character State /// <summary> /// The state of a character. /// </summary> public enum CharacterState { /// <summary> /// Ready to perform an action, and playing the idle animation /// </summary> Idle, /// <summary> /// Walking in the world. /// </summary> Walking, /// <summary> /// In defense mode /// </summary> Defending, /// <summary> /// Performing Dodge Animation /// </summary> Dodging, /// <summary> /// Performing Hit Animation /// </summary> Hit, /// <summary> /// Dead, but still playing the dying animation. /// </summary> Dying, /// <summary> /// Dead, with the dead animation. /// </summary> Dead, } /// <summary> /// The state of this character. /// </summary> private CharacterState state = CharacterState.Idle; /// <summary> /// The state of this character. /// </summary> [ContentSerializerIgnore] public CharacterState State { get { return state; } set { state = value; } } /// <summary> /// Returns true if the character is dead or dying. /// </summary> public bool IsDeadOrDying { get { return ((State == CharacterState.Dying) || (State == CharacterState.Dead)); } } #endregion #region Map Data /// <summary> /// The position of this object on the map. /// </summary> private Point mapPosition; /// <summary> /// The position of this object on the map. /// </summary> [ContentSerializerIgnore] public Point MapPosition { get { return mapPosition; } set { mapPosition = value; } } /// <summary> /// The orientation of this object on the map. /// </summary> private Direction direction; /// <summary> /// The orientation of this object on the map. /// </summary> [ContentSerializerIgnore] public Direction Direction { get { return direction; } set { direction = value; } } #endregion #region Graphics Data /// <summary> /// The animating sprite for the map view of this character. /// </summary> private AnimatingSprite mapSprite; /// <summary> /// The animating sprite for the map view of this character. /// </summary> [ContentSerializer(Optional = true)] public AnimatingSprite MapSprite { get { return mapSprite; } set { mapSprite = value; } } /// <summary> /// The animating sprite for the map view of this character as it walks. /// </summary> /// <remarks> /// If this object is null, then the animations are taken from MapSprite. /// </remarks> private AnimatingSprite walkingSprite; /// <summary> /// The animating sprite for the map view of this character as it walks. /// </summary> /// <remarks> /// If this object is null, then the animations are taken from MapSprite. /// </remarks> [ContentSerializer(Optional=true)] public AnimatingSprite WalkingSprite { get { return walkingSprite; } set { walkingSprite = value; } } /// <summary> /// Reset the animations for this character. /// </summary> public virtual void ResetAnimation(bool isWalking) { state = isWalking ? CharacterState.Walking : CharacterState.Idle; if (mapSprite != null) { if (isWalking && mapSprite["Walk" + Direction.ToString()] != null) { mapSprite.PlayAnimation("Walk", Direction); } else { mapSprite.PlayAnimation("Idle", Direction); } } if (walkingSprite != null) { if (isWalking && walkingSprite["Walk" + Direction.ToString()] != null) { walkingSprite.PlayAnimation("Walk", Direction); } else { walkingSprite.PlayAnimation("Idle", Direction); } } } /// <summary> /// The small blob shadow that is rendered under the characters. /// </summary> private Texture2D shadowTexture; /// <summary> /// The small blob shadow that is rendered under the characters. /// </summary> [ContentSerializerIgnore] public Texture2D ShadowTexture { get { return shadowTexture; } set { shadowTexture = value; } } #endregion #region Standard Animation Data /// <summary> /// The default idle-animation interval for the animating map sprite. /// </summary> private int mapIdleAnimationInterval = 200; /// <summary> /// The default idle-animation interval for the animating map sprite. /// </summary> [ContentSerializer(Optional=true)] public int MapIdleAnimationInterval { get { return mapIdleAnimationInterval; } set { mapIdleAnimationInterval = value; } } /// <summary> /// Add the standard character idle animations to this character. /// </summary> private void AddStandardCharacterIdleAnimations() { if (mapSprite != null) { mapSprite.AddAnimation(new Animation("IdleSouth", 1, 6, MapIdleAnimationInterval, true)); mapSprite.AddAnimation(new Animation("IdleSouthwest", 7, 12, MapIdleAnimationInterval, true)); mapSprite.AddAnimation(new Animation("IdleWest", 13, 18, MapIdleAnimationInterval, true)); mapSprite.AddAnimation(new Animation("IdleNorthwest", 19, 24, MapIdleAnimationInterval, true)); mapSprite.AddAnimation(new Animation("IdleNorth", 25, 30, MapIdleAnimationInterval, true)); mapSprite.AddAnimation(new Animation("IdleNortheast", 31, 36, MapIdleAnimationInterval, true)); mapSprite.AddAnimation(new Animation("IdleEast", 37, 42, MapIdleAnimationInterval, true)); mapSprite.AddAnimation(new Animation("IdleSoutheast", 43, 48, MapIdleAnimationInterval, true)); } } /// <summary> /// The default walk-animation interval for the animating map sprite. /// </summary> private int mapWalkingAnimationInterval = 80; /// <summary> /// The default walk-animation interval for the animating map sprite. /// </summary> [ContentSerializer(Optional = true)] public int MapWalkingAnimationInterval { get { return mapWalkingAnimationInterval; } set { mapWalkingAnimationInterval = value; } } /// <summary> /// Add the standard character walk animations to this character. /// </summary> private void AddStandardCharacterWalkingAnimations() { AnimatingSprite sprite = (walkingSprite == null ? mapSprite : walkingSprite); if (sprite != null) { sprite.AddAnimation(new Animation("WalkSouth", 1, 6, MapWalkingAnimationInterval, true)); sprite.AddAnimation(new Animation("WalkSouthwest", 7, 12, MapWalkingAnimationInterval, true)); sprite.AddAnimation(new Animation("WalkWest", 13, 18, MapWalkingAnimationInterval, true)); sprite.AddAnimation(new Animation("WalkNorthwest", 19, 24, MapWalkingAnimationInterval, true)); sprite.AddAnimation(new Animation("WalkNorth", 25, 30, MapWalkingAnimationInterval, true)); sprite.AddAnimation(new Animation("WalkNortheast", 31, 36, MapWalkingAnimationInterval, true)); sprite.AddAnimation(new Animation("WalkEast", 37, 42, MapWalkingAnimationInterval, true)); sprite.AddAnimation(new Animation("WalkSoutheast", 43, 48, MapWalkingAnimationInterval, true)); } } #endregion #region Content Type Reader /// <summary> /// Reads a Character object from the content pipeline. /// </summary> public class CharacterReader : ContentTypeReader<Character> { /// <summary> /// Reads a Character object from the content pipeline. /// </summary> protected override Character Read(ContentReader input, Character existingInstance) { Character character = existingInstance; if (character == null) { throw new ArgumentNullException("existingInstance"); } input.ReadRawObject<WorldObject>(character as WorldObject); character.MapIdleAnimationInterval = input.ReadInt32(); character.MapSprite = input.ReadObject<AnimatingSprite>(); if (character.MapSprite != null) { character.MapSprite.SourceOffset = new Vector2( character.MapSprite.SourceOffset.X - 32 * ScaledVector2.ScaleFactor, character.MapSprite.SourceOffset.Y - 32 * ScaledVector2.ScaleFactor); } character.AddStandardCharacterIdleAnimations(); character.MapWalkingAnimationInterval = input.ReadInt32(); character.WalkingSprite = input.ReadObject<AnimatingSprite>(); if (character.WalkingSprite != null) { character.WalkingSprite.SourceOffset = new Vector2( character.WalkingSprite.SourceOffset.X - 32 * ScaledVector2.ScaleFactor, character.WalkingSprite.SourceOffset.Y - 32 * ScaledVector2.ScaleFactor); } character.AddStandardCharacterWalkingAnimations(); character.ResetAnimation(false); character.shadowTexture = input.ContentManager.Load<Texture2D>( @"Textures\Characters\CharacterShadow"); return character; } } #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.Buffers; using System.Text; using Xunit; namespace System.Buffers.Tests { public class Reader_SkipDelimiter { [Fact] public void TryReadTo_SkipDelimiter() { byte[] expected = Encoding.UTF8.GetBytes("This is our ^|understanding^|"); ReadOnlySequence<byte> bytes = BufferFactory.CreateUtf8("This is our ^|understanding^|| you see."); BufferReader<byte> reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out ReadOnlySpan<byte> span, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(expected, span.ToArray()); Assert.True(reader.IsNext((byte)' ')); Assert.Equal(30, reader.Consumed); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(expected, span.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(29, reader.Consumed); // Put the skip delimiter in another segment bytes = BufferFactory.CreateUtf8("This is our ^|understanding", "^|| you see."); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(expected, span.ToArray()); Assert.True(reader.IsNext((byte)' ')); Assert.Equal(30, reader.Consumed); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(expected, span.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(29, reader.Consumed); // Put the skip delimiter at the end of the segment bytes = BufferFactory.CreateUtf8("This is our ^|understanding^", "|| you see."); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(expected, span.ToArray()); Assert.True(reader.IsNext((byte)' ')); Assert.Equal(30, reader.Consumed); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(expected, span.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(29, reader.Consumed); // No trailing data bytes = BufferFactory.CreateUtf8("This is our ^|understanding^||"); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(expected, span.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(29, reader.Consumed); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(expected, span.ToArray()); Assert.True(reader.End); Assert.Equal(30, reader.Consumed); // All delimiters skipped bytes = BufferFactory.CreateUtf8("This is our ^|understanding^|"); reader = new BufferReader<byte>(bytes); Assert.False(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(0, reader.Consumed); reader = new BufferReader<byte>(bytes); Assert.False(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(0, reader.Consumed); bytes = BufferFactory.CreateUtf8("abc^|de|"); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(Encoding.UTF8.GetBytes("abc^|de"), span.ToArray()); Assert.True(reader.End); Assert.Equal(8, reader.Consumed); // Escape leads bytes = BufferFactory.CreateUtf8("^|a|b"); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(Encoding.UTF8.GetBytes("^|a"), span.ToArray()); Assert.True(reader.IsNext((byte)'b')); Assert.Equal(4, reader.Consumed); // Delimiter starts second segment. bytes = BufferFactory.CreateUtf8("^", "|a|b"); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(Encoding.UTF8.GetBytes("^|a"), span.ToArray()); Assert.True(reader.IsNext((byte)'b')); Assert.Equal(4, reader.Consumed); } [Fact] public void TryReadTo_SkipDelimiter_Runs() { ReadOnlySequence<byte> bytes = BufferFactory.CreateUtf8("abc^^|def"); BufferReader<byte> reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out ReadOnlySpan<byte> span, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(5, reader.Consumed); // Split after escape char bytes = BufferFactory.CreateUtf8("abc^^", "|def"); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(5, reader.Consumed); // Split before and after escape char bytes = BufferFactory.CreateUtf8("abc^", "^", "|def"); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(5, reader.Consumed); // Check advance past delimiter reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(Encoding.UTF8.GetBytes("abc^^"), span.ToArray()); Assert.True(reader.IsNext((byte)'d')); Assert.Equal(6, reader.Consumed); // Leading run of 2 bytes = BufferFactory.CreateUtf8("^^|abc"); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(Encoding.UTF8.GetBytes("^^"), span.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(2, reader.Consumed); // Leading run of 3 bytes = BufferFactory.CreateUtf8("^^^|abc"); reader = new BufferReader<byte>(bytes); Assert.False(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.True(reader.IsNext((byte)'^')); Assert.Equal(0, reader.Consumed); // Trailing run of 3 bytes = BufferFactory.CreateUtf8("abc^^^|"); reader = new BufferReader<byte>(bytes); Assert.False(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.True(reader.IsNext((byte)'a')); Assert.Equal(0, reader.Consumed); // Trailing run of 3, split bytes = BufferFactory.CreateUtf8("abc^^^", "|"); reader = new BufferReader<byte>(bytes); Assert.False(reader.TryReadTo(out span, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.True(reader.IsNext((byte)'a')); Assert.Equal(0, reader.Consumed); } [Fact] public void TryReadTo_SkipDelimiter_ReadOnlySequence() { byte[] expected = Encoding.UTF8.GetBytes("This is our ^|understanding^|"); ReadOnlySequence<byte> bytes = BufferFactory.CreateUtf8("This is our ^|understanding^|| you see."); BufferReader<byte> reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out ReadOnlySequence<byte> sequence, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(expected, sequence.ToArray()); Assert.True(reader.IsNext((byte)' ')); Assert.Equal(30, reader.Consumed); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(expected, sequence.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(29, reader.Consumed); // Put the skip delimiter in another segment bytes = BufferFactory.CreateUtf8("This is our ^|understanding", "^|| you see."); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(expected, sequence.ToArray()); Assert.True(reader.IsNext((byte)' ')); Assert.Equal(30, reader.Consumed); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(expected, sequence.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(29, reader.Consumed); // Put the skip delimiter at the end of the segment bytes = BufferFactory.CreateUtf8("This is our ^|understanding^", "|| you see."); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(expected, sequence.ToArray()); Assert.True(reader.IsNext((byte)' ')); Assert.Equal(30, reader.Consumed); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(expected, sequence.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(29, reader.Consumed); // No trailing data bytes = BufferFactory.CreateUtf8("This is our ^|understanding^||"); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(expected, sequence.ToArray()); Assert.True(reader.IsNext((byte)'|')); Assert.Equal(29, reader.Consumed); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(expected, sequence.ToArray()); Assert.True(reader.End); Assert.Equal(30, reader.Consumed); // All delimiters skipped bytes = BufferFactory.CreateUtf8("This is our ^|understanding^|"); reader = new BufferReader<byte>(bytes); Assert.False(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: false)); Assert.Equal(0, reader.Consumed); reader = new BufferReader<byte>(bytes); Assert.False(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(0, reader.Consumed); bytes = BufferFactory.CreateUtf8("abc^|de|"); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(Encoding.UTF8.GetBytes("abc^|de"), sequence.ToArray()); Assert.True(reader.End); Assert.Equal(8, reader.Consumed); // Escape leads bytes = BufferFactory.CreateUtf8("^|a|b"); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(Encoding.UTF8.GetBytes("^|a"), sequence.ToArray()); Assert.True(reader.IsNext((byte)'b')); Assert.Equal(4, reader.Consumed); // Delimiter starts second segment. bytes = BufferFactory.CreateUtf8("^", "|a|b"); reader = new BufferReader<byte>(bytes); Assert.True(reader.TryReadTo(out sequence, (byte)'|', (byte)'^', advancePastDelimiter: true)); Assert.Equal(Encoding.UTF8.GetBytes("^|a"), sequence.ToArray()); Assert.True(reader.IsNext((byte)'b')); Assert.Equal(4, reader.Consumed); } } }
namespace Microsoft.Protocols.TestSuites.MS_ASHTTP { using System; using System.Collections.Generic; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; using Response = Microsoft.Protocols.TestSuites.Common.Response; /// <summary> /// This scenario is designed to test HTTP POST commands with positive response. /// </summary> [TestClass] public class S01_HTTPPOSTPositive : TestSuiteBase { #region Class initialize and clean up /// <summary> /// Initialize the class. /// </summary> /// <param name="testContext">VSTS test context.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Clear the class. /// </summary> [ClassCleanup] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test cases /// <summary> /// This test case is intended to validate the Content-Type response header. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC01_VerifyContentTypeResponseHeader() { #region Synchronize the collection hierarchy via FolderSync command. FolderSyncResponse folderSyncResponse = this.CallFolderSyncCommand(); Site.Assert.IsNotNull(folderSyncResponse.Headers["Content-Type"], "The Content-Type header should not be null."); #endregion // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R219"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R219 // If the content type is WBXML, this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( "application/vnd.ms-sync.wbxml", folderSyncResponse.Headers["Content-Type"], 219, @"[In Content-Type] If the response body is WBXML, the value of this [Content-Type] header MUST be ""application/vnd.ms-sync.wbxml""."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R229"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R229 // If the content type is WBXML, this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( "application/vnd.ms-sync.wbxml", folderSyncResponse.Headers["Content-Type"], 229, @"[In Response Body] The response body [except the Autodiscover command], if any, is in WBXML."); } /// <summary> /// This test case is intended to validate the Content-Encoding response header. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC02_VerifyContentEncodingResponseHeader() { #region Call FolderSync command without setting AcceptEncoding header. FolderSyncResponse folderSyncResponse = this.CallFolderSyncCommand(); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R412"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R412 // If the Content-Encoding header doesn't exist, this requirement can be captured. Site.CaptureRequirementIfIsFalse( folderSyncResponse.Headers.ToString().Contains("Content-Encoding"), 412, @"[In Response Headers] [[Header] Content-Encoding [is] required when the content is compressed ;] otherwise, this header [Content-Encoding] is not included."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R215"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R215 // If the Content-Encoding header doesn't exist, this requirement can be captured. Site.CaptureRequirementIfIsFalse( folderSyncResponse.Headers.ToString().Contains("Content-Encoding"), 215, @"[In Content-Encoding] Otherwise [if the response body is not compressed], it [Content-Encoding header] is omitted."); #endregion #region Call ConfigureRequestPrefixFields to set the AcceptEncoding header to "gzip". IDictionary<HTTPPOSTRequestPrefixField, string> requestPrefix = new Dictionary<HTTPPOSTRequestPrefixField, string>(); requestPrefix.Add(HTTPPOSTRequestPrefixField.AcceptEncoding, "gzip"); this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); #endregion #region Call FolderSync command. folderSyncResponse = this.LoopCallFolderSyncCommand(); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R197"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R197 // If the Content-Encoding header is gzip, this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( "gzip", folderSyncResponse.Headers["Content-Encoding"], 197, @"[In Response Headers] [Header] Content-Encoding [is] required when the content is compressed [; otherwise, this header [Content-Encoding] is not included]."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R214"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R214 // If the Content-Encoding header is gzip, this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( "gzip", folderSyncResponse.Headers["Content-Encoding"], 214, @"[In Content-Encoding] This [Content-Encoding] header is required if the response body is compressed."); #endregion } /// <summary> /// This test case is intended to validate the AttachmentName command parameter with Base64 encoding query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC03_CommandParameter_AttachmentName_Base64() { Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 14.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("16.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 16.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); this.VerifyGetAttachmentsCommandParameter(QueryValueType.Base64); } /// <summary> /// This test case is intended to validate the AttachmentName command parameter with Plain Text query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC04_CommandParameter_AttachmentName_PlainText() { Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 14.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("16.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 16.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); SendStringResponse getAttachmentResponse = this.VerifyGetAttachmentsCommandParameter(QueryValueType.PlainText); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R115"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R115 // The GetAttachment command executes successfully when the AttachmentName command parameter is set, so this requirement can be captured. Site.CaptureRequirement( 115, @"[In Command-Specific URI Parameters] [Parameter] AttachmentName [is used by] GetAttachment."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R487"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R487 // The GetAttachment command executes successfully when the AttachmentName command parameter is set, so this requirement can be captured. Site.CaptureRequirement( 487, @"[In Command-Specific URI Parameters] [Parameter] AttachmentName [is described as] A string that specifies the name of the attachment file to be retrieved. "); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R230"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R230 // The GetAttachment command response has no xml body, so this requirement can be captured. Site.CaptureRequirementIfIsFalse( this.IsXml(getAttachmentResponse.ResponseDataXML), 230, @"[In Response Body] Three commands have no XML body in certain contexts: GetAttachment, [Sync, and Ping]."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R490"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R490 // The GetAttachment command was executed successfully, so this requirement can be captured. Site.CaptureRequirement( 490, @"[In Command Codes] [Command] GetAttachment retrieves an e-mail attachment from the server."); } /// <summary> /// This test case is intended to validate the SaveInSent, CollectionId and ItemId command parameters with Base64 encoding query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC05_CommandParameter_SaveInSent_Base64() { this.VerifySaveInSentCommandParameter(QueryValueType.Base64, "1", "1", "1"); } /// <summary> /// This test case is intended to validate the SaveInSent, CollectionId and ItemId command parameters with Plain Text query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC06_CommandParameter_SaveInSent_PlainText() { this.VerifySaveInSentCommandParameter(QueryValueType.PlainText, "T", "F", null); } /// <summary> /// This test case is intended to validate the LongId command parameter with Base64 encoding query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC07_CommandParameter_LongId_Base64() { this.VerifyLongIdCommandParameter(QueryValueType.Base64); } /// <summary> /// This test case is intended to validate the LongId command parameter with Plain Text query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC08_CommandParameter_LongId_PlainText() { this.VerifyLongIdCommandParameter(QueryValueType.PlainText); } /// <summary> /// This test case is intended to validate the Occurrence command parameter with Base64 encoding query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC09_CommandParameter_Occurrence_Base64() { #region User3 calls SendMail to send a meeting request to User2. IDictionary<HTTPPOSTRequestPrefixField, string> requestPrefix = new Dictionary<HTTPPOSTRequestPrefixField, string>(); string sendMailSubject = Common.GenerateResourceName(this.Site, "SendMail"); string smartForwardSubject = Common.GenerateResourceName(this.Site, "SmartForward"); // Call ConfigureRequestPrefixFields to change the QueryValueType to Base64. requestPrefix.Add(HTTPPOSTRequestPrefixField.QueryValueType, QueryValueType.Base64.ToString()); this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); // Switch the current user to user3 and synchronize the collection hierarchy. this.SwitchUser(this.UserThreeInformation, true); // Call SendMail command to send the meeting request to User2. this.SendMeetingRequest(sendMailSubject); #endregion #region User2 calls MeetingResponse command to accept the received meeting request and forward it to User1. // Call ConfigureRequestPrefixFields to switch the credential to User2 and synchronize the collection hierarchy. this.SwitchUser(this.UserTwoInformation, true); // Call Sync command to get the ServerId of the received meeting request. string itemServerId = this.LoopToSyncItem(this.UserTwoInformation.InboxCollectionId, sendMailSubject, true); // Add the received item to the item collection of User2. CreatedItems inboxItemForUserTwo = new CreatedItems { CollectionId = this.UserTwoInformation.InboxCollectionId }; inboxItemForUserTwo.ItemSubject.Add(sendMailSubject); this.UserTwoInformation.UserCreatedItems.Add(inboxItemForUserTwo); // Check the calendar item if is exist. string calendarItemServerId = this.LoopToSyncItem(this.UserTwoInformation.CalendarCollectionId, sendMailSubject, true); CreatedItems calendarItemForUserTwo = new CreatedItems { CollectionId = this.UserTwoInformation.CalendarCollectionId }; calendarItemForUserTwo.ItemSubject.Add(sendMailSubject); this.UserTwoInformation.UserCreatedItems.Add(calendarItemForUserTwo); // Call MeetingResponse command to accept the received meeting request. this.CallMeetingResponseCommand(this.UserTwoInformation.InboxCollectionId, itemServerId); // The accepted meeting request will be moved to Delete Items folder. itemServerId = this.LoopToSyncItem(this.UserTwoInformation.DeletedItemsCollectionId, sendMailSubject, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R432"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R432 // MeetingResponse command is executed successfully, so this requirement can be captured. Site.CaptureRequirementIfIsNotNull( itemServerId, 432, @"[In Command Codes] [Command] MeetingResponse [is] used to accept [, tentatively accept , or decline] a meeting request in the user's Inbox folder."); // Remove the inboxItemForUserTwo object from the clean up list since it has been moved to Delete Items folder. this.UserTwoInformation.UserCreatedItems.Remove(inboxItemForUserTwo); this.AddCreatedItemToCollection("User2", this.UserTwoInformation.DeletedItemsCollectionId, sendMailSubject); // Call SmartForward command to forward the meeting to User1 string startTime = (string)this.GetElementValueFromSyncResponse(this.UserTwoInformation.CalendarCollectionId, calendarItemServerId, Response.ItemsChoiceType8.StartTime); string occurrence = TestSuiteHelper.ConvertInstanceIdFormat(startTime); string userOneMailboxAddress = Common.GetMailAddress(this.UserOneInformation.UserName, this.UserOneInformation.UserDomain); string userTwoMailboxAddress = Common.GetMailAddress(this.UserTwoInformation.UserName, this.UserTwoInformation.UserDomain); this.CallSmartForwardCommand(userTwoMailboxAddress, userOneMailboxAddress, itemServerId, smartForwardSubject, null, null, occurrence); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R513"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R513 // SmartForward command executed successfully with setting Occurrence command parameter, so this requirement can be captured. Site.CaptureRequirement( 513, @"[In Command-Specific URI Parameters] [Parameter] Occurrence [is described as] A string that specifies the ID of a particular occurrence in a recurring meeting."); this.AddCreatedItemToCollection("User3", this.UserThreeInformation.DeletedItemsCollectionId, "Meeting Forward Notification: " + smartForwardSubject); #endregion #region User1 gets the forwarded meeting request // Call ConfigureRequestPrefixFields to switch the credential to User1 and synchronize the collection hierarchy. this.SwitchUser(this.UserOneInformation, true); this.AddCreatedItemToCollection("User1", this.UserOneInformation.InboxCollectionId, smartForwardSubject); this.AddCreatedItemToCollection("User1", this.UserOneInformation.CalendarCollectionId, smartForwardSubject); // Call Sync command to get the ServerId of the received meeting request. this.LoopToSyncItem(this.UserOneInformation.InboxCollectionId, smartForwardSubject, true); // Call Sync command to get the ServerId of the calendar item. this.LoopToSyncItem(this.UserOneInformation.CalendarCollectionId, smartForwardSubject, true); #endregion #region User3 gets the Meeting Forward Notification email in the Deleted Items folder. // Call ConfigureRequestPrefixFields to switch the credential to User3 and synchronize the collection hierarchy. this.SwitchUser(this.UserThreeInformation, false); // Call Sync command to get the ServerId of the received meeting request and the notification email. this.LoopToSyncItem(this.UserThreeInformation.DeletedItemsCollectionId, "Meeting Forward Notification: " + smartForwardSubject, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R119"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R119 // SmartForward command executed successfully with setting Occurrence command parameter, so this requirement can be captured. Site.CaptureRequirement( 119, @"[In Command-Specific URI Parameters] [Parameter] Occurrence [is used by] SmartForward."); #endregion #region Reset the query value type. requestPrefix[HTTPPOSTRequestPrefixField.QueryValueType] = Common.GetConfigurationPropertyValue("HeaderEncodingType", this.Site); HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); #endregion } /// <summary> /// This test case is intended to validate the Occurrence command parameter with Plain Text query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC10_CommandParameter_Occurrence_PlainText() { #region User3 calls SendMail to send a meeting request to User2 IDictionary<HTTPPOSTRequestPrefixField, string> requestPrefix = new Dictionary<HTTPPOSTRequestPrefixField, string>(); string sendMailSubject = Common.GenerateResourceName(this.Site, "SendMail"); string smartReplySubject = Common.GenerateResourceName(this.Site, "SmartReply"); // Call ConfigureRequestPrefixFields to change the QueryValueType. requestPrefix.Add(HTTPPOSTRequestPrefixField.QueryValueType, QueryValueType.PlainText.ToString()); this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); // Switch the current user to user3 and synchronize the collection hierarchy. this.SwitchUser(this.UserThreeInformation, true); // Call SendMail command to send the meeting request to User2. this.SendMeetingRequest(sendMailSubject); #endregion #region User2 calls SmartReply command to reply the request to User3 with Occurrence command parameter // Call ConfigureRequestPrefixFields to switch the credential to User2 and synchronize the collection hierarchy. this.SwitchUser(this.UserTwoInformation, true); // Call Sync command to get the ServerId of the received meeting request. string itemServerId = this.LoopToSyncItem(this.UserTwoInformation.InboxCollectionId, sendMailSubject, true); // Add the received item to the item collection of User2. CreatedItems inboxItemForUserTwo = new CreatedItems { CollectionId = this.UserTwoInformation.InboxCollectionId }; inboxItemForUserTwo.ItemSubject.Add(sendMailSubject); this.UserTwoInformation.UserCreatedItems.Add(inboxItemForUserTwo); // Call Sync command to get the ServerId of the calendar item. string calendarItemServerId = this.LoopToSyncItem(this.UserTwoInformation.CalendarCollectionId, sendMailSubject, true); CreatedItems calendarItemForUserTwo = new CreatedItems { CollectionId = this.UserTwoInformation.CalendarCollectionId }; calendarItemForUserTwo.ItemSubject.Add(sendMailSubject); this.UserTwoInformation.UserCreatedItems.Add(calendarItemForUserTwo); // Call SmartReply command with the Occurrence command parameter. string startTime = (string)this.GetElementValueFromSyncResponse(this.UserTwoInformation.CalendarCollectionId, calendarItemServerId, Response.ItemsChoiceType8.StartTime); string occurrence = TestSuiteHelper.ConvertInstanceIdFormat(startTime); string userTwoMailboxAddress = Common.GetMailAddress(this.UserTwoInformation.UserName, this.UserTwoInformation.UserDomain); string userThreeMailboxAddress = Common.GetMailAddress(this.UserThreeInformation.UserName, this.UserThreeInformation.UserDomain); this.CallSmartReplyCommand(userTwoMailboxAddress, userThreeMailboxAddress, itemServerId, smartReplySubject, null, null, occurrence); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R513"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R513 // SmartReply command executed successfully with setting Occurrence command parameter, so this requirement can be captured. Site.CaptureRequirement( 513, @"[In Command-Specific URI Parameters] [Parameter] Occurrence [is described as] A string that specifies the ID of a particular occurrence in a recurring meeting."); #endregion #region User3 gets the reply mail // Call ConfigureRequestPrefixFields to switch the credential to User3 and synchronize the collection hierarchy. this.SwitchUser(this.UserThreeInformation, false); // Call Sync command to get the ServerId of the received the reply. this.LoopToSyncItem(this.UserThreeInformation.InboxCollectionId, smartReplySubject, true); this.AddCreatedItemToCollection("User3", this.UserThreeInformation.InboxCollectionId, smartReplySubject); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R529"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R529 // SmartReply command executed successfully with setting Occurrence command parameter, so this requirement can be captured. Site.CaptureRequirement( 529, @"[In Command-Specific URI Parameters] [Parameter] Occurrence [is used by] SmartReply."); #endregion #region Reset the query value type and user credential. requestPrefix[HTTPPOSTRequestPrefixField.QueryValueType] = Common.GetConfigurationPropertyValue("HeaderEncodingType", this.Site); HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); this.SwitchUser(this.UserOneInformation, false); #endregion } /// <summary> /// This test case is intended to validate the FolderSync, FolderCreate, FolderUpdate and FolderDelete command codes. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC11_CommandCode_FolderRelatedCommands() { string folderNameToCreate = Common.GenerateResourceName(this.Site, "CreatedFolder"); string folderNameToUpdate = Common.GenerateResourceName(this.Site, "UpdatedFolder"); #region Call FolderSync command to synchronize the folder hierarchy. FolderSyncResponse folderSyncResponse = this.CallFolderSyncCommand(); #endregion #region Call FolderCreate command to create a sub folder under Inbox folder. FolderCreateResponse folderCreateResponse = this.CallFolderCreateCommand(folderSyncResponse.ResponseData.SyncKey, folderNameToCreate, Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Inbox, Site)); #endregion #region Call FolderSync command to synchronize the folder hierarchy. folderSyncResponse = this.CallFolderSyncCommand(); // Get the created folder name using the ServerId returned in FolderSync response. string createdFolderName = this.GetFolderFromFolderSyncResponse(folderSyncResponse, folderCreateResponse.ResponseData.ServerId, "DisplayName"); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R493"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R493 // The created folder could be got in FolderSync response, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( folderNameToCreate, createdFolderName, 493, @"[In Command Codes] [Command] FolderCreate creates an e-mail, [calendar, or contacts folder] on the server."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R491"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R491 // R493 is captured, so this requirement can be captured directly. Site.CaptureRequirement( 491, @"[In Command Codes] [Command] FolderSync synchronizes the folder hierarchy."); // Call the Sync command with latest SyncKey without change in folder. SyncStore syncResponse = this.CallSyncCommand(folderCreateResponse.ResponseData.ServerId); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R482"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R482 // If response is not in xml, this requirement can be captured. Site.CaptureRequirementIfIsNull( syncResponse.SyncKey, 482, @"[In Response Body] Three commands have no XML body in certain contexts: [GetAttachment,] Sync [, and Ping]."); #endregion #region Call FolderUpdate command to update the name of the created folder to a new folder name and move the created folder to SentItems folder. this.CallFolderUpdateCommand(folderSyncResponse.ResponseData.SyncKey, folderCreateResponse.ResponseData.ServerId, folderNameToUpdate, Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.SentItems, this.Site)); #endregion #region Call FolderSync command to synchronize the folder hierarchy. folderSyncResponse = this.CallFolderSyncCommand(); // Get the updated folder name using the ServerId returned in FolderSync response. string updatedFolderName = this.GetFolderFromFolderSyncResponse(folderSyncResponse, folderCreateResponse.ResponseData.ServerId, "DisplayName"); string updatedParentId = this.GetFolderFromFolderSyncResponse(folderSyncResponse, folderCreateResponse.ResponseData.ServerId, "ParentId"); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R431"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R431 // The folder name is updated to the specified name, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( folderNameToUpdate, updatedFolderName, 431, @"[In Command Codes] [Command] FolderUpdate is used to rename folders."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R68"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R68 // The folder has been moved to the new created folder, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.SentItems, this.Site), updatedParentId, 68, @"[In Command Codes] [Command] FolderUpdate moves a folder from one location to another on the server."); #endregion #region Call FolderDelete to delete the folder from the server. this.CallFolderDeleteCommand(folderSyncResponse.ResponseData.SyncKey, folderCreateResponse.ResponseData.ServerId); #endregion #region Call FolderSync command to synchronize the folder hierarchy. folderSyncResponse = this.CallFolderSyncCommand(); // Get the created folder name using the ServerId returned in FolderSync response. updatedFolderName = this.GetFolderFromFolderSyncResponse(folderSyncResponse, folderCreateResponse.ResponseData.ServerId, "DisplayName"); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R496"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R496 // The folder with the specified ServerId could not be got, so this requirement can be captured. Site.CaptureRequirementIfIsNull( updatedFolderName, 496, @"[In Command Codes] [Command] FolderDelete deletes a folder from the server."); #endregion } /// <summary> /// This test case is intended to validate the Ping, MoveItems, GetItemEstimate and ItemOperations command codes. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC12_CommandCode_ItemRelatedCommands() { #region Call ConfigureRequestPrefixFields to change the query value type to Base64. IDictionary<HTTPPOSTRequestPrefixField, string> requestPrefix = new Dictionary<HTTPPOSTRequestPrefixField, string>(); requestPrefix.Add(HTTPPOSTRequestPrefixField.QueryValueType, QueryValueType.Base64.ToString()); this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); #endregion #region Call SendMail command to send email to User2. string sendMailSubject = Common.GenerateResourceName(Site, "SendMail"); string folderNameToCreate = Common.GenerateResourceName(Site, "CreatedFolder"); string userOneMailboxAddress = Common.GetMailAddress(this.UserOneInformation.UserName, this.UserOneInformation.UserDomain); string userTwoMailboxAddress = Common.GetMailAddress(this.UserTwoInformation.UserName, this.UserTwoInformation.UserDomain); // Call SendMail command to send email to User2. this.CallSendMailCommand(userOneMailboxAddress, userTwoMailboxAddress, sendMailSubject, null); #endregion #region Call Ping command for changes that would require the client to resynchronize. // Switch the user to User2 and synchronize the collection hierarchy. this.SwitchUser(this.UserTwoInformation, true); // Call FolderSync command to synchronize the collection hierarchy. FolderSyncResponse folderSyncResponse = this.CallFolderSyncCommand(); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R428"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R428 // The received email could not be got by FolderSync command, so this requirement can be captured. Site.CaptureRequirementIfIsFalse( folderSyncResponse.ResponseDataXML.Contains(sendMailSubject), 428, @"[In Command Codes] But [command] FolderSync does not synchronize the items in the folders."); // Call Ping command for changes of Inbox folder. PingResponse pingResponse = this.CallPingCommand(this.UserTwoInformation.InboxCollectionId); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R504"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R504 // The Status of the Ping command is 2 which means this folder needs to be synced, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( "2", pingResponse.ResponseData.Status.ToString(), 504, @"[In Command Codes] [Command] Ping requests that the server monitor specified folders for changes that would require the client to resynchronize."); #endregion #region Get the ServerId of the received email. // Call Sync command to get the ServerId of the received email. string receivedItemServerId = this.LoopToSyncItem(this.UserTwoInformation.InboxCollectionId, sendMailSubject, true); #endregion #region Call FolderCreate command to create a sub folder under Inbox folder. FolderCreateResponse folderCreateResponse = this.CallFolderCreateCommand(folderSyncResponse.ResponseData.SyncKey, folderNameToCreate, this.UserTwoInformation.InboxCollectionId); // Get the ServerId of the created folder. string createdFolder = folderCreateResponse.ResponseData.ServerId; #endregion #region Move the received email from Inbox folder to the created folder. this.CallMoveItemsCommand(receivedItemServerId, this.UserTwoInformation.InboxCollectionId, createdFolder); #endregion #region Get the moved email in the created folder. // Call Sync command to get the received email. receivedItemServerId = this.LoopToSyncItem(createdFolder, sendMailSubject, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R499"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R499 // The moved email could be got in the new created folder, so this requirement can be captured. Site.CaptureRequirementIfIsNotNull( receivedItemServerId, 499, @"[In Command Codes] [Command] MoveItems moves items from one folder to another."); #endregion #region Call ItemOperation command to fetch the email in Sent Items folder with AcceptMultiPart command parameter. SendStringResponse itemOperationResponse = this.CallItemOperationsCommand(createdFolder, receivedItemServerId, true); Site.Assert.IsNotNull(itemOperationResponse.Headers["Content-Type"], "The Content-Type header should not be null."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R94"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R94 // The content is in multipart, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( "application/vnd.ms-sync.multipart", itemOperationResponse.Headers["Content-Type"], 94, @"[In Command Parameters] [When flag] AcceptMultiPart [value is] 0x02, [the meaning is] setting this flag [AcceptMultiPart] to instruct the server to return the requested item in multipart format."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R95"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R95 // R94 can be captured, so this requirement can be captured directly. Site.CaptureRequirement( 95, @"[In Command Parameters] [When flag] AcceptMultiPart [value is] 0x02, [it is] valid for ItemOperations."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R534"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R534 // R94 can be captured, so this requirement can be captured directly. Site.CaptureRequirement( 534, @"[In Command Parameters] [Parameter] Options [ is used by] ItemOperations."); #endregion #region Call FolderDelete to delete a folder from the server. this.CallFolderDeleteCommand(folderCreateResponse.ResponseData.SyncKey, createdFolder); #endregion #region Reset the query value type and user credential. requestPrefix[HTTPPOSTRequestPrefixField.QueryValueType] = Common.GetConfigurationPropertyValue("HeaderEncodingType", this.Site); this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); this.SwitchUser(this.UserOneInformation, false); #endregion } /// <summary> /// This test case is intended to validate the ResolveRecipients and Settings command codes. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC13_CommandCode_UserRelatedCommands() { #region Call ResolveRecipients command. object[] items = new object[] { Common.GetConfigurationPropertyValue("User1Name", Site) }; ResolveRecipientsRequest resolveRecipientsRequest = Common.CreateResolveRecipientsRequest(items); SendStringResponse resolveRecipientsResponse = HTTPAdapter.HTTPPOST(CommandName.ResolveRecipients, null, resolveRecipientsRequest.GetRequestDataSerializedXML()); // Check the command is executed successfully. this.CheckResponseStatus(resolveRecipientsResponse.ResponseDataXML); #endregion #region Call Settings command. SettingsRequest settingsRequest = Common.CreateSettingsRequest(); SendStringResponse settingsResponse = HTTPAdapter.HTTPPOST(CommandName.Settings, null, settingsRequest.GetRequestDataSerializedXML()); // Check the command is executed successfully. this.CheckResponseStatus(settingsResponse.ResponseDataXML); #endregion } /// <summary> /// This test case is intended to validate the ValidateCert command code. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC14_CommandCode_ValidateCert() { #region Call ValidateCert command. ValidateCertRequest validateCertRequest = Common.CreateValidateCertRequest(); SendStringResponse validateCertResponse = HTTPAdapter.HTTPPOST(CommandName.ValidateCert, null, validateCertRequest.GetRequestDataSerializedXML()); // Check the command is executed successfully. this.CheckResponseStatus(validateCertResponse.ResponseDataXML); #endregion } #endregion #region Private methods /// <summary> /// Loop to call FolderSync command and get the response till FolderSync Response's Content-Encoding header is gzip. /// </summary> /// <returns>The response of FolderSync command.</returns> private FolderSyncResponse LoopCallFolderSyncCommand() { #region Loop to call FolderSync int counter = 0; int waitTime = int.Parse(Common.GetConfigurationPropertyValue("WaitTime", Site)); int upperBound = int.Parse(Common.GetConfigurationPropertyValue("RetryCount", Site)); FolderSyncResponse folderSyncResponse = this.CallFolderSyncCommand(); while (counter < upperBound && !folderSyncResponse.Headers.ToString().Contains("Content-Encoding")) { System.Threading.Thread.Sleep(waitTime); folderSyncResponse = this.CallFolderSyncCommand(); counter++; } #endregion #region Call ConfigureRequestPrefixFields to reset the AcceptEncoding header. IDictionary<HTTPPOSTRequestPrefixField, string> requestPrefix = new Dictionary<HTTPPOSTRequestPrefixField, string>(); requestPrefix[HTTPPOSTRequestPrefixField.AcceptEncoding] = null; this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); #endregion #region Return FolderSync response Site.Assert.IsNotNull(folderSyncResponse.Headers["Content-Encoding"], "The Content-Encoding header should exist in the response headers after retry {0} times", counter); return folderSyncResponse; #endregion } #endregion } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Text; namespace OpenSim.Framework.Serialization { /// <summary> /// Temporary code to produce a tar archive in tar v7 format /// </summary> public class TarArchiveWriter { //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected static ASCIIEncoding m_asciiEncoding = new ASCIIEncoding(); /// <summary> /// Binary writer for the underlying stream /// </summary> protected BinaryWriter m_bw; public TarArchiveWriter(Stream s) { m_bw = new BinaryWriter(s); } /// <summary> /// Write a directory entry to the tar archive. We can only handle one path level right now! /// </summary> /// <param name="dirName"></param> public void WriteDir(string dirName) { // Directories are signalled by a final / if (!dirName.EndsWith("/")) dirName += "/"; WriteFile(dirName, new byte[0]); } /// <summary> /// Write a file to the tar archive /// </summary> /// <param name="filePath"></param> /// <param name="data"></param> public void WriteFile(string filePath, string data) { WriteFile(filePath, m_asciiEncoding.GetBytes(data)); } /// <summary> /// Write a file to the tar archive /// </summary> /// <param name="filePath"></param> /// <param name="data"></param> public void WriteFile(string filePath, byte[] data) { if (filePath.Length > 100) WriteEntry("././@LongLink", m_asciiEncoding.GetBytes(filePath), 'L'); char fileType; if (filePath.EndsWith("/")) { fileType = '5'; } else { fileType = '0'; } WriteEntry(filePath, data, fileType); } /// <summary> /// Finish writing the raw tar archive data to a stream. The stream will be closed on completion. /// </summary> /// <param name="s">Stream to which to write the data</param> /// <returns></returns> public void Close() { //m_log.Debug("[TAR ARCHIVE WRITER]: Writing final consecutive 0 blocks"); // Write two consecutive 0 blocks to end the archive byte[] finalZeroPadding = new byte[1024]; lock (m_bw) { m_bw.Write(finalZeroPadding); m_bw.Flush(); m_bw.Close(); } } public static byte[] ConvertDecimalToPaddedOctalBytes(int d, int padding) { string oString = ""; while (d > 0) { oString = Convert.ToString((byte)'0' + d & 7) + oString; d >>= 3; } while (oString.Length < padding) { oString = "0" + oString; } byte[] oBytes = m_asciiEncoding.GetBytes(oString); return oBytes; } /// <summary> /// Write a particular entry /// </summary> /// <param name="filePath"></param> /// <param name="data"></param> /// <param name="fileType"></param> protected void WriteEntry(string filePath, byte[] data, char fileType) { byte[] header = new byte[512]; // file path field (100) byte[] nameBytes = m_asciiEncoding.GetBytes(filePath); int nameSize = (nameBytes.Length >= 100) ? 100 : nameBytes.Length; Array.Copy(nameBytes, header, nameSize); // file mode (8) byte[] modeBytes = m_asciiEncoding.GetBytes("0000777"); Array.Copy(modeBytes, 0, header, 100, 7); // owner user id (8) byte[] ownerIdBytes = m_asciiEncoding.GetBytes("0000764"); Array.Copy(ownerIdBytes, 0, header, 108, 7); // group user id (8) byte[] groupIdBytes = m_asciiEncoding.GetBytes("0000764"); Array.Copy(groupIdBytes, 0, header, 116, 7); // file size in bytes (12) int fileSize = data.Length; //m_log.DebugFormat("[TAR ARCHIVE WRITER]: File size of {0} is {1}", filePath, fileSize); byte[] fileSizeBytes = ConvertDecimalToPaddedOctalBytes(fileSize, 11); Array.Copy(fileSizeBytes, 0, header, 124, 11); // last modification time (12) byte[] lastModTimeBytes = m_asciiEncoding.GetBytes("11017037332"); Array.Copy(lastModTimeBytes, 0, header, 136, 11); // entry type indicator (1) header[156] = m_asciiEncoding.GetBytes(new char[] { fileType })[0]; Array.Copy(m_asciiEncoding.GetBytes("0000000"), 0, header, 329, 7); Array.Copy(m_asciiEncoding.GetBytes("0000000"), 0, header, 337, 7); // check sum for header block (8) [calculated last] Array.Copy(m_asciiEncoding.GetBytes(" "), 0, header, 148, 8); int checksum = 0; foreach (byte b in header) { checksum += b; } //m_log.DebugFormat("[TAR ARCHIVE WRITER]: Decimal header checksum is {0}", checksum); byte[] checkSumBytes = ConvertDecimalToPaddedOctalBytes(checksum, 6); Array.Copy(checkSumBytes, 0, header, 148, 6); header[154] = 0; lock (m_bw) { // Write out header m_bw.Write(header); // Write out data m_bw.Write(data); if (data.Length % 512 != 0) { int paddingRequired = 512 - (data.Length % 512); //m_log.DebugFormat("[TAR ARCHIVE WRITER]: Padding data with {0} bytes", paddingRequired); byte[] padding = new byte[paddingRequired]; m_bw.Write(padding); } } } } }
// 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.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Runtime.InteropServices; using System.Security; namespace System.Reflection.Emit { // TypeNameBuilder is NOT thread safe NOR reliable internal class TypeNameBuilder { internal enum Format { ToString, FullName, AssemblyQualifiedName, } #region QCalls [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr CreateTypeNameBuilder(); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void ReleaseTypeNameBuilder(IntPtr pAQN); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void OpenGenericArguments(IntPtr tnb); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void CloseGenericArguments(IntPtr tnb); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void OpenGenericArgument(IntPtr tnb); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void CloseGenericArgument(IntPtr tnb); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void AddName(IntPtr tnb, string name); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void AddPointer(IntPtr tnb); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void AddByRef(IntPtr tnb); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void AddSzArray(IntPtr tnb); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void AddArray(IntPtr tnb, int rank); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void AddAssemblySpec(IntPtr tnb, string assemblySpec); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void ToString(IntPtr tnb, StringHandleOnStack retString); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void Clear(IntPtr tnb); #endregion #region Static Members // TypeNameBuilder is NOT thread safe NOR reliable [System.Security.SecuritySafeCritical] // auto-generated internal static string ToString(Type type, Format format) { if (format == Format.FullName || format == Format.AssemblyQualifiedName) { if (!type.IsGenericTypeDefinition && type.ContainsGenericParameters) return null; } TypeNameBuilder tnb = new TypeNameBuilder(CreateTypeNameBuilder()); tnb.Clear(); tnb.ConstructAssemblyQualifiedNameWorker(type, format); string toString = tnb.ToString(); tnb.Dispose(); return toString; } #endregion #region Private Data Members private IntPtr m_typeNameBuilder; #endregion #region Constructor private TypeNameBuilder(IntPtr typeNameBuilder) { m_typeNameBuilder = typeNameBuilder; } [System.Security.SecurityCritical] // auto-generated internal void Dispose() { ReleaseTypeNameBuilder(m_typeNameBuilder); } #endregion #region private Members [System.Security.SecurityCritical] // auto-generated private void AddElementType(Type elementType) { if (elementType.HasElementType) AddElementType(elementType.GetElementType()); if (elementType.IsPointer) AddPointer(); else if (elementType.IsByRef) AddByRef(); else if (elementType.IsSzArray) AddSzArray(); else if (elementType.IsArray) AddArray(elementType.GetArrayRank()); } [System.Security.SecurityCritical] // auto-generated private void ConstructAssemblyQualifiedNameWorker(Type type, Format format) { Type rootType = type; while (rootType.HasElementType) rootType = rootType.GetElementType(); // Append namespace + nesting + name List<Type> nestings = new List<Type>(); for (Type t = rootType; t != null; t = t.IsGenericParameter ? null : t.DeclaringType) nestings.Add(t); for (int i = nestings.Count - 1; i >= 0; i--) { Type enclosingType = nestings[i]; string name = enclosingType.Name; if (i == nestings.Count - 1 && enclosingType.Namespace != null && enclosingType.Namespace.Length != 0) name = enclosingType.Namespace + "." + name; AddName(name); } // Append generic arguments if (rootType.IsGenericType && (!rootType.IsGenericTypeDefinition || format == Format.ToString)) { Type[] genericArguments = rootType.GetGenericArguments(); OpenGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { Format genericArgumentsFormat = format == Format.FullName ? Format.AssemblyQualifiedName : format; OpenGenericArgument(); ConstructAssemblyQualifiedNameWorker(genericArguments[i], genericArgumentsFormat); CloseGenericArgument(); } CloseGenericArguments(); } // Append pointer, byRef and array qualifiers AddElementType(type); if (format == Format.AssemblyQualifiedName) AddAssemblySpec(type.Module.Assembly.FullName); } [System.Security.SecurityCritical] // auto-generated private void OpenGenericArguments() { OpenGenericArguments(m_typeNameBuilder); } [System.Security.SecurityCritical] // auto-generated private void CloseGenericArguments() { CloseGenericArguments(m_typeNameBuilder); } [System.Security.SecurityCritical] // auto-generated private void OpenGenericArgument() { OpenGenericArgument(m_typeNameBuilder); } [System.Security.SecurityCritical] // auto-generated private void CloseGenericArgument() { CloseGenericArgument(m_typeNameBuilder); } [System.Security.SecurityCritical] // auto-generated private void AddName(string name) { AddName(m_typeNameBuilder, name); } [System.Security.SecurityCritical] // auto-generated private void AddPointer() { AddPointer(m_typeNameBuilder); } [System.Security.SecurityCritical] // auto-generated private void AddByRef() { AddByRef(m_typeNameBuilder); } [System.Security.SecurityCritical] // auto-generated private void AddSzArray() { AddSzArray(m_typeNameBuilder); } [System.Security.SecurityCritical] // auto-generated private void AddArray(int rank) { AddArray(m_typeNameBuilder, rank); } [System.Security.SecurityCritical] // auto-generated private void AddAssemblySpec(string assemblySpec) { AddAssemblySpec(m_typeNameBuilder, assemblySpec); } [System.Security.SecuritySafeCritical] // auto-generated public override string ToString() { string ret = null; ToString(m_typeNameBuilder, JitHelpers.GetStringHandleOnStack(ref ret)); return ret; } [System.Security.SecurityCritical] // auto-generated private void Clear() { Clear(m_typeNameBuilder); } #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.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { // Encapsulates all logic about convertibility between types. // // WARNING: These methods do not precisely match the spec. // WARNING: For example most also return true for identity conversions, // WARNING: FExpRefConv includes all Implicit and Explicit reference conversions. internal static class CConversions { // WARNING: These methods do not precisely match the spec. // WARNING: For example most also return true for identity conversions, // WARNING: FExpRefConv includes all Implicit and Explicit reference conversions. /*************************************************************************************************** Determine whether there is an implicit reference conversion from typeSrc to typeDst. This is when the source is a reference type and the destination is a base type of the source. Note that typeDst.IsRefType() may still return false (when both are type parameters). ***************************************************************************************************/ public static bool FImpRefConv(CType typeSrc, CType typeDst) => typeSrc.IsReferenceType && SymbolLoader.HasIdentityOrImplicitReferenceConversion(typeSrc, typeDst); /*************************************************************************************************** Determine whether there is an explicit or implicit reference conversion (or identity conversion) from typeSrc to typeDst. This is when: 13.2.3 Explicit reference conversions The explicit reference conversions are: * From object to any reference-type. * From any class-type S to any class-type T, provided S is a base class of T. * From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T. * From any interface-type S to any class-type T, provided T is not sealed or provided T implements S. * From any interface-type S to any interface-type T, provided S is not derived from T. * From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true: o S and T differ only in element type. (In other words, S and T have the same number of dimensions.) o An explicit reference conversion exists from SE to TE. * From System.Array and the interfaces it implements, to any array-type. * From System.Delegate and the interfaces it implements, to any delegate-type. * From a one-dimensional array-type S[] to System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and their base interfaces, provided there is an explicit reference conversion from S to T. * From a generic delegate type S to generic delegate type T, provided all of the follow are true: o Both types are constructed generic types of the same generic delegate type, D<X1,... Xk>.That is, S is D<S1,... Sk> and T is D<T1,... Tk>. o S is not compatible with or identical to T. o If type parameter Xi is declared to be invariant then Si must be identical to Ti. o If type parameter Xi is declared to be covariant ("out") then Si must be convertible to Ti via an identify conversion, implicit reference conversion, or explicit reference conversion. o If type parameter Xi is declared to be contravariant ("in") then either Si must be identical to Ti, or Si and Ti must both be reference types. * From System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and their base interfaces to a one-dimensional array-type S[], provided there is an implicit or explicit reference conversion from S[] to System.Collections.Generic.IList<T> or System.Collections.Generic.IReadOnlyList<T>. This is precisely when either S and T are the same type or there is an implicit or explicit reference conversion from S to T. For a type-parameter T that is known to be a reference type (25.7), the following explicit reference conversions exist: * From the effective base class C of T to T and from any base class of C to T. * From any interface-type to T. * From T to any interface-type I provided there isn't already an implicit reference conversion from T to I. * From a type-parameter U to T provided that T depends on U (25.7). [Note: Since T is known to be a reference type, within the scope of T, the run-time type of U will always be a reference type, even if U is not known to be a reference type at compile-time. end note] * Both src and dst are reference types and there is a builtin explicit conversion from src to dst. * Or src is a reference type and dst is a base type of src (in which case the conversion is implicit as well). * Or dst is a reference type and src is a base type of dst. The latter two cases can happen with type variables even though the other type variable is not a reference type. ***************************************************************************************************/ public static bool FExpRefConv(CType typeSrc, CType typeDst) { Debug.Assert(typeSrc != null); Debug.Assert(typeDst != null); if (typeSrc.IsReferenceType && typeDst.IsReferenceType) { // is there an implicit reference conversion in either direction? // this handles the bulk of the cases ... if (SymbolLoader.HasIdentityOrImplicitReferenceConversion(typeSrc, typeDst) || SymbolLoader.HasIdentityOrImplicitReferenceConversion(typeDst, typeSrc)) { return true; } // For a type-parameter T that is known to be a reference type (25.7), the following explicit reference conversions exist: // * From any interface-type to T. // * From T to any interface-type I provided there isn't already an implicit reference conversion from T to I. if (typeSrc.IsInterfaceType && typeDst is TypeParameterType || typeSrc is TypeParameterType && typeDst.IsInterfaceType) { return true; } // * From any class-type S to any interface-type T, provided S is not sealed // * From any interface-type S to any class-type T, provided T is not sealed // * From any interface-type S to any interface-type T, provided S is not derived from T. if (typeSrc is AggregateType atSrc && typeDst is AggregateType atDst) { AggregateSymbol aggSrc = atSrc.OwningAggregate; AggregateSymbol aggDest = atDst.OwningAggregate; if ((aggSrc.IsClass() && !aggSrc.IsSealed() && aggDest.IsInterface()) || (aggSrc.IsInterface() && aggDest.IsClass() && !aggDest.IsSealed()) || (aggSrc.IsInterface() && aggDest.IsInterface())) { return true; } } if (typeSrc is ArrayType arrSrc) { // * From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true: // o S and T differ only in element type. (In other words, S and T have the same number of dimensions.) // o An explicit reference conversion exists from SE to TE. if (typeDst is ArrayType arrDst) { return arrSrc.Rank == arrDst.Rank && arrSrc.IsSZArray == arrDst.IsSZArray && FExpRefConv(arrSrc.ElementType, arrDst.ElementType); } // * From a one-dimensional array-type S[] to System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> // and their base interfaces, provided there is an explicit reference conversion from S to T. if (!arrSrc.IsSZArray || !typeDst.IsInterfaceType) { return false; } AggregateType aggDst = (AggregateType)typeDst; TypeArray typeArgsAll = aggDst.TypeArgsAll; if (typeArgsAll.Count != 1) { return false; } AggregateSymbol aggIList = SymbolLoader.GetPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = SymbolLoader.GetPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !SymbolLoader.IsBaseAggregate(aggIList, aggDst.OwningAggregate)) && (aggIReadOnlyList == null || !SymbolLoader.IsBaseAggregate(aggIReadOnlyList, aggDst.OwningAggregate))) { return false; } return FExpRefConv(arrSrc.ElementType, typeArgsAll[0]); } if (typeDst is ArrayType arrayDest && typeSrc is AggregateType aggtypeSrc) { // * From System.Array and the interfaces it implements, to any array-type. if (SymbolLoader.HasIdentityOrImplicitReferenceConversion(SymbolLoader.GetPredefindType(PredefinedType.PT_ARRAY), typeSrc)) { return true; } // * From System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and their base interfaces to a // one-dimensional array-type S[], provided there is an implicit or explicit reference conversion from S[] to // System.Collections.Generic.IList<T> or System.Collections.Generic.IReadOnlyList<T>. This is precisely when either S and T // are the same type or there is an implicit or explicit reference conversion from S to T. if (!arrayDest.IsSZArray || !typeSrc.IsInterfaceType || aggtypeSrc.TypeArgsAll.Count != 1) { return false; } AggregateSymbol aggIList = SymbolLoader.GetPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = SymbolLoader.GetPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !SymbolLoader.IsBaseAggregate(aggIList, aggtypeSrc.OwningAggregate)) && (aggIReadOnlyList == null || !SymbolLoader.IsBaseAggregate(aggIReadOnlyList, aggtypeSrc.OwningAggregate))) { return false; } CType typeArr = arrayDest.ElementType; CType typeLst = aggtypeSrc.TypeArgsAll[0]; Debug.Assert(!(typeArr is MethodGroupType)); return typeArr == typeLst || FExpRefConv(typeArr, typeLst); } if (HasGenericDelegateExplicitReferenceConversion(typeSrc, typeDst)) { return true; } } else if (typeSrc.IsReferenceType) { // conversion of T . U, where T : class, U // .. these constraints implies where U : class return SymbolLoader.HasIdentityOrImplicitReferenceConversion(typeSrc, typeDst); } else if (typeDst.IsReferenceType) { // conversion of T . U, where U : class, T // .. these constraints implies where T : class return SymbolLoader.HasIdentityOrImplicitReferenceConversion(typeDst, typeSrc); } return false; } /*************************************************************************************************** There exists an explicit conversion ... * From a generic delegate type S to generic delegate type T, provided all of the follow are true: o Both types are constructed generic types of the same generic delegate type, D<X1,... Xk>.That is, S is D<S1,... Sk> and T is D<T1,... Tk>. o S is not compatible with or identical to T. o If type parameter Xi is declared to be invariant then Si must be identical to Ti. o If type parameter Xi is declared to be covariant ("out") then Si must be convertible to Ti via an identify conversion, implicit reference conversion, or explicit reference conversion. o If type parameter Xi is declared to be contravariant ("in") then either Si must be identical to Ti, or Si and Ti must both be reference types. ***************************************************************************************************/ public static bool HasGenericDelegateExplicitReferenceConversion(CType source, CType target) => target is AggregateType aggTarget && HasGenericDelegateExplicitReferenceConversion(source, aggTarget); public static bool HasGenericDelegateExplicitReferenceConversion(CType pSource, AggregateType pTarget) { if (!(pSource is AggregateType aggSrc) || !aggSrc.IsDelegateType || !pTarget.IsDelegateType || aggSrc.OwningAggregate != pTarget.OwningAggregate || SymbolLoader.HasIdentityOrImplicitReferenceConversion(aggSrc, pTarget)) { return false; } TypeArray pTypeParams = aggSrc.OwningAggregate.GetTypeVarsAll(); TypeArray pSourceArgs = aggSrc.TypeArgsAll; TypeArray pTargetArgs = pTarget.TypeArgsAll; Debug.Assert(pTypeParams.Count == pSourceArgs.Count); Debug.Assert(pTypeParams.Count == pTargetArgs.Count); for (int iParam = 0; iParam < pTypeParams.Count; ++iParam) { CType pSourceArg = pSourceArgs[iParam]; CType pTargetArg = pTargetArgs[iParam]; // If they're identical then this one is automatically good, so skip it. // If we have an error type, then we're in some fault tolerance. Let it through. if (pSourceArg == pTargetArg) { continue; } TypeParameterType pParam = (TypeParameterType)pTypeParams[iParam]; if (pParam.Invariant) { return false; } if (pParam.Covariant) { if (!FExpRefConv(pSourceArg, pTargetArg)) { return false; } } else if (pParam.Contravariant) { if (!pSourceArg.IsReferenceType || !pTargetArg.IsReferenceType) { return false; } } } return true; } /*************************************************************************************************** 13.1.1 Identity conversion An identity conversion converts from any type to the same type. This conversion exists only such that an entity that already has a required type can be said to be convertible to that type. Always returns false if the types are error, anonymous method, or method group ***************************************************************************************************/ /*************************************************************************************************** Determines whether there is a boxing conversion from typeSrc to typeDst 13.1.5 Boxing conversions A boxing conversion permits any non-nullable-value-type to be implicitly converted to the type object or System.ValueType or to any interface-type implemented by the non-nullable-value-type, and any enum type to be implicitly converted to System.Enum as well. ... An enum can be boxed to the type System.Enum, since that is the direct base class for all enums (21.4). A struct or enum can be boxed to the type System.ValueType, since that is the direct base class for all structs (18.3.2) and a base class for all enums. A nullable-type has a boxing conversion to the same set of types to which the nullable-type's underlying type has boxing conversions. For a type-parameter T that is not known to be a reference type (25.7), the following conversions involving T are considered to be boxing conversions at compile-time. At run-time, if T is a value type, the conversion is executed as a boxing conversion. At run-time, if T is a reference type, the conversion is executed as an implicit reference conversion or identity conversion. * From T to its effective base class C, from T to any base class of C, and from T to any interface implemented by C. [Note: C will be one of the types System.Object, System.ValueType, or System.Enum (otherwise T would be known to be a reference type and 13.1.4 would apply instead of this clause). end note] * From T to an interface-type I in T's effective interface set and from T to any base interface of I. ***************************************************************************************************/ /*************************************************************************************************** Determines whether there is a wrapping conversion from typeSrc to typeDst 13.7 Conversions involving nullable types The following terms are used in the subsequent sections: * The term wrapping denotes the process of packaging a value, of type T, in an instance of type T?. A value x of type T is wrapped to type T? by evaluating the expression new T?(x). ***************************************************************************************************/ public static bool FWrappingConv(CType typeSrc, CType typeDst) => typeDst is NullableType nubDst && typeSrc == nubDst.UnderlyingType; /*************************************************************************************************** Determines whether there is a unwrapping conversion from typeSrc to typeDst 13.7 Conversions involving nullable types The following terms are used in the subsequent sections: * The term unwrapping denotes the process of obtaining the value, of type T, contained in an instance of type T?. A value x of type T? is unwrapped to type T by evaluating the expression x.Value. Attempting to unwrap a null instance causes a System.InvalidOperationException to be thrown. ***************************************************************************************************/ public static bool FUnwrappingConv(CType typeSrc, CType typeDst) { return FWrappingConv(typeDst, typeSrc); } } }
using System; using System.Diagnostics; using System.Text; using u8 = System.Byte; using u16 = System.UInt16; using u32 = System.UInt32; using sqlite3_int64 = System.Int64; namespace Community.CsharpSqlite { using sqlite3_stmt = Sqlite3.Vdbe; public partial class Sqlite3 { /* ** 2005 May 25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the implementation of the sqlite3_prepare() ** interface, and routines that contribute to loading the database schema ** from disk. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ //#include "sqliteInt.h" /* ** Fill the InitData structure with an error message that indicates ** that the database is corrupt. */ static void corruptSchema( InitData pData, /* Initialization context */ string zObj, /* Object being parsed at the point of error */ string zExtra /* Error information */ ) { sqlite3 db = pData.db; if ( /* 0 == db.mallocFailed && */ ( db.flags & SQLITE_RecoveryMode ) == 0 ) { { if ( zObj == null ) { zObj = "?"; #if SQLITE_OMIT_UTF16 if (ENC(db) != SQLITE_UTF8) zObj =encnames[(ENC(db))].zName; #endif } sqlite3SetString( ref pData.pzErrMsg, db, "malformed database schema (%s)", zObj ); if ( !String.IsNullOrEmpty( zExtra ) ) { pData.pzErrMsg = sqlite3MAppendf( db, pData.pzErrMsg , "%s - %s", pData.pzErrMsg, zExtra ); } } pData.rc = //db.mallocFailed != 0 ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT(); } } /* ** This is the callback routine for the code that initializes the ** database. See sqlite3Init() below for additional information. ** This routine is also called from the OP_ParseSchema opcode of the VDBE. ** ** Each callback contains the following information: ** ** argv[0] = name of thing being created ** argv[1] = root page number for table or index. 0 for trigger or view. ** argv[2] = SQL text for the CREATE statement. ** */ static int sqlite3InitCallback( object pInit, sqlite3_int64 argc, object p2, object NotUsed ) { string[] argv = (string[])p2; InitData pData = (InitData)pInit; sqlite3 db = pData.db; int iDb = pData.iDb; Debug.Assert( argc == 3 ); UNUSED_PARAMETER2( NotUsed, argc ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); DbClearProperty( db, iDb, DB_Empty ); //if ( db.mallocFailed != 0 ) //{ // corruptSchema( pData, argv[0], "" ); // return 1; //} Debug.Assert( iDb >= 0 && iDb < db.nDb ); if ( argv == null ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ if ( argv[1] == null ) { corruptSchema( pData, argv[0], "" ); } else if ( !String.IsNullOrEmpty( argv[2] ) ) { /* Call the parser to process a CREATE TABLE, INDEX or VIEW. ** But because db.init.busy is set to 1, no VDBE code is generated ** or executed. All the parser does is build the internal data ** structures that describe the table, index, or view. */ int rc; sqlite3_stmt pStmt = null; #if !NDEBUG || SQLITE_COVERAGE_TEST //TESTONLY(int rcp); /* Return code from sqlite3_prepare() */ int rcp; #endif Debug.Assert( db.init.busy != 0 ); db.init.iDb = iDb; db.init.newTnum = sqlite3Atoi( argv[1] ); db.init.orphanTrigger = 0; //TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0); string sDummy = null; #if !NDEBUG || SQLITE_COVERAGE_TEST rcp = sqlite3_prepare( db, argv[2], -1, ref pStmt, ref sDummy ); #else sqlite3_prepare(db, argv[2], -1, ref pStmt, ref sDummy); #endif rc = db.errCode; #if !NDEBUG || SQLITE_COVERAGE_TEST Debug.Assert( ( rc & 0xFF ) == ( rcp & 0xFF ) ); #endif db.init.iDb = 0; if ( SQLITE_OK != rc ) { if ( db.init.orphanTrigger != 0 ) { Debug.Assert( iDb == 1 ); } else { pData.rc = rc; if ( rc == SQLITE_NOMEM ) { // db.mallocFailed = 1; } else if ( rc != SQLITE_INTERRUPT && ( rc & 0xFF ) != SQLITE_LOCKED ) { corruptSchema( pData, argv[0], sqlite3_errmsg( db ) ); } } } sqlite3_finalize( pStmt ); } else if ( argv[0] == null || argv[0] == "" ) { corruptSchema( pData, null, null ); } else { /* If the SQL column is blank it means this is an index that ** was created to be the PRIMARY KEY or to fulfill a UNIQUE ** constraint for a CREATE TABLE. The index should have already ** been created when we processed the CREATE TABLE. All we have ** to do here is record the root page number for that index. */ Index pIndex; pIndex = sqlite3FindIndex( db, argv[0], db.aDb[iDb].zName ); if ( pIndex == null ) { /* This can occur if there exists an index on a TEMP table which ** has the same name as another index on a permanent index. Since ** the permanent table is hidden by the TEMP table, we can also ** safely ignore the index on the permanent table. */ /* Do Nothing */ ; } else if ( sqlite3GetInt32( argv[1], ref pIndex.tnum ) == false ) { corruptSchema( pData, argv[0], "invalid rootpage" ); } } return 0; } /* ** Attempt to read the database schema and initialize internal ** data structures for a single database file. The index of the ** database file is given by iDb. iDb==0 is used for the main ** database. iDb==1 should never be used. iDb>=2 is used for ** auxiliary databases. Return one of the SQLITE_ error codes to ** indicate success or failure. */ static int sqlite3InitOne( sqlite3 db, int iDb, ref string pzErrMsg ) { int rc; int i; int size; Table pTab; Db pDb; string[] azArg = new string[4]; u32[] meta = new u32[5]; InitData initData = new InitData(); string zMasterSchema; string zMasterName; int openedTransaction = 0; /* ** The master database table has a structure like this */ string master_schema = "CREATE TABLE sqlite_master(\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")" ; #if !SQLITE_OMIT_TEMPDB string temp_master_schema = "CREATE TEMP TABLE sqlite_temp_master(\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")" ; #else //#define temp_master_schema 0 #endif Debug.Assert( iDb >= 0 && iDb < db.nDb ); Debug.Assert( db.aDb[iDb].pSchema != null ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); Debug.Assert( iDb == 1 || sqlite3BtreeHoldsMutex( db.aDb[iDb].pBt ) ); /* zMasterSchema and zInitScript are set to point at the master schema ** and initialisation script appropriate for the database being ** initialised. zMasterName is the name of the master table. */ if ( OMIT_TEMPDB == 0 && iDb == 1 ) { zMasterSchema = temp_master_schema; } else { zMasterSchema = master_schema; } zMasterName = SCHEMA_TABLE( iDb ); /* Construct the schema tables. */ azArg[0] = zMasterName; azArg[1] = "1"; azArg[2] = zMasterSchema; azArg[3] = ""; initData.db = db; initData.iDb = iDb; initData.rc = SQLITE_OK; initData.pzErrMsg = pzErrMsg; sqlite3InitCallback( initData, 3, azArg, null ); if ( initData.rc != 0 ) { rc = initData.rc; goto error_out; } pTab = sqlite3FindTable( db, zMasterName, db.aDb[iDb].zName ); if ( ALWAYS( pTab ) ) { pTab.tabFlags |= TF_Readonly; } /* Create a cursor to hold the database open */ pDb = db.aDb[iDb]; if ( pDb.pBt == null ) { if ( OMIT_TEMPDB == 0 && ALWAYS( iDb == 1 ) ) { DbSetProperty( db, 1, DB_SchemaLoaded ); } return SQLITE_OK; } /* If there is not already a read-only (or read-write) transaction opened ** on the b-tree database, open one now. If a transaction is opened, it ** will be closed before this function returns. */ sqlite3BtreeEnter( pDb.pBt ); if ( !sqlite3BtreeIsInReadTrans( pDb.pBt ) ) { rc = sqlite3BtreeBeginTrans( pDb.pBt, 0 ); if ( rc != SQLITE_OK ) { #if SQLITE_OMIT_WAL if (pDb.pBt.pBt.pSchema.file_format == 2) sqlite3SetString( ref pzErrMsg, db, "%s (wal format detected)", sqlite3ErrStr( rc ) ); else sqlite3SetString( ref pzErrMsg, db, "%s", sqlite3ErrStr( rc ) ); #else sqlite3SetString( ref pzErrMsg, db, "%s", sqlite3ErrStr( rc ) ); #endif goto initone_error_out; } openedTransaction = 1; } /* Get the database meta information. ** ** Meta values are as follows: ** meta[0] Schema cookie. Changes with each schema change. ** meta[1] File format of schema layer. ** meta[2] Size of the page cache. ** meta[3] Largest rootpage (auto/incr_vacuum mode) ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE ** meta[5] User version ** meta[6] Incremental vacuum mode ** meta[7] unused ** meta[8] unused ** meta[9] unused ** ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to ** the possible values of meta[BTREE_TEXT_ENCODING-1]. */ for ( i = 0; i < ArraySize( meta ); i++ ) { sqlite3BtreeGetMeta( pDb.pBt, i + 1, ref meta[i] ); } pDb.pSchema.schema_cookie = (int)meta[BTREE_SCHEMA_VERSION - 1]; /* If opening a non-empty database, check the text encoding. For the ** main database, set sqlite3.enc to the encoding of the main database. ** For an attached db, it is an error if the encoding is not the same ** as sqlite3.enc. */ if ( meta[BTREE_TEXT_ENCODING - 1] != 0 ) { /* text encoding */ if ( iDb == 0 ) { u8 encoding; /* If opening the main database, set ENC(db). */ encoding = (u8)( meta[BTREE_TEXT_ENCODING - 1] & 3 ); if ( encoding == 0 ) encoding = SQLITE_UTF8; db.aDb[0].pSchema.enc = encoding; //ENC( db ) = encoding; db.pDfltColl = sqlite3FindCollSeq( db, SQLITE_UTF8, "BINARY", 0 ); } else { /* If opening an attached database, the encoding much match ENC(db) */ if ( meta[BTREE_TEXT_ENCODING - 1] != ENC( db ) ) { sqlite3SetString( ref pzErrMsg, db, "attached databases must use the same" + " text encoding as main database" ); rc = SQLITE_ERROR; goto initone_error_out; } } } else { DbSetProperty( db, iDb, DB_Empty ); } pDb.pSchema.enc = ENC( db ); if ( pDb.pSchema.cache_size == 0 ) { size = sqlite3AbsInt32((int)meta[BTREE_DEFAULT_CACHE_SIZE - 1]); if ( size == 0 ) { size = SQLITE_DEFAULT_CACHE_SIZE; } pDb.pSchema.cache_size = size; sqlite3BtreeSetCacheSize( pDb.pBt, pDb.pSchema.cache_size ); } /* ** file_format==1 Version 3.0.0. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants */ pDb.pSchema.file_format = (u8)meta[BTREE_FILE_FORMAT - 1]; if ( pDb.pSchema.file_format == 0 ) { pDb.pSchema.file_format = 1; } if ( pDb.pSchema.file_format > SQLITE_MAX_FILE_FORMAT ) { sqlite3SetString( ref pzErrMsg, db, "unsupported file format" ); rc = SQLITE_ERROR; goto initone_error_out; } /* Ticket #2804: When we open a database in the newer file format, ** clear the legacy_file_format pragma flag so that a VACUUM will ** not downgrade the database and thus invalidate any descending ** indices that the user might have created. */ if ( iDb == 0 && meta[BTREE_FILE_FORMAT - 1] >= 4 ) { db.flags &= ~SQLITE_LegacyFileFmt; } /* Read the schema information out of the schema tables */ Debug.Assert( db.init.busy != 0 ); { string zSql; zSql = sqlite3MPrintf( db, "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid", db.aDb[iDb].zName, zMasterName ); #if ! SQLITE_OMIT_AUTHORIZATION { int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); xAuth = db.xAuth; db.xAuth = 0; #endif rc = sqlite3_exec( db, zSql, (dxCallback)sqlite3InitCallback, initData, 0 ); pzErrMsg = initData.pzErrMsg; #if ! SQLITE_OMIT_AUTHORIZATION db.xAuth = xAuth; } #endif if ( rc == SQLITE_OK ) rc = initData.rc; sqlite3DbFree( db, ref zSql ); #if !SQLITE_OMIT_ANALYZE if ( rc == SQLITE_OK ) { sqlite3AnalysisLoad( db, iDb ); } #endif } //if ( db.mallocFailed != 0 ) //{ // rc = SQLITE_NOMEM; // sqlite3ResetInternalSchema( db, -1 ); //} if ( rc == SQLITE_OK || ( db.flags & SQLITE_RecoveryMode ) != 0 ) { /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider ** the schema loaded, even if errors occurred. In this situation the ** current sqlite3_prepare() operation will fail, but the following one ** will attempt to compile the supplied statement against whatever subset ** of the schema was loaded before the error occurred. The primary ** purpose of this is to allow access to the sqlite_master table ** even when its contents have been corrupted. */ DbSetProperty( db, iDb, DB_SchemaLoaded ); rc = SQLITE_OK; } /* Jump here for an error that occurs after successfully allocating ** curMain and calling sqlite3BtreeEnter(). For an error that occurs ** before that point, jump to error_out. */ initone_error_out: if ( openedTransaction != 0 ) { sqlite3BtreeCommit( pDb.pBt ); } sqlite3BtreeLeave( pDb.pBt ); error_out: if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM ) { // db.mallocFailed = 1; } return rc; } /* ** Initialize all database files - the main database file, the file ** used to store temporary tables, and any additional database files ** created using ATTACH statements. Return a success code. If an ** error occurs, write an error message into pzErrMsg. ** ** After a database is initialized, the DB_SchemaLoaded bit is set ** bit is set in the flags field of the Db structure. If the database ** file was of zero-length, then the DB_Empty flag is also set. */ static int sqlite3Init( sqlite3 db, ref string pzErrMsg ) { int i, rc; bool commit_internal = !( ( db.flags & SQLITE_InternChanges ) != 0 ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); rc = SQLITE_OK; db.init.busy = 1; for ( i = 0; rc == SQLITE_OK && i < db.nDb; i++ ) { if ( DbHasProperty( db, i, DB_SchemaLoaded ) || i == 1 ) continue; rc = sqlite3InitOne( db, i, ref pzErrMsg ); if ( rc != 0 ) { sqlite3ResetInternalSchema( db, i ); } } /* Once all the other databases have been initialised, load the schema ** for the TEMP database. This is loaded last, as the TEMP database ** schema may contain references to objects in other databases. */ #if !SQLITE_OMIT_TEMPDB if ( rc == SQLITE_OK && ALWAYS( db.nDb > 1 ) && !DbHasProperty( db, 1, DB_SchemaLoaded ) ) { rc = sqlite3InitOne( db, 1, ref pzErrMsg ); if ( rc != 0 ) { sqlite3ResetInternalSchema( db, 1 ); } } #endif db.init.busy = 0; if ( rc == SQLITE_OK && commit_internal ) { sqlite3CommitInternalChanges( db ); } return rc; } /* ** This routine is a no-op if the database schema is already initialised. ** Otherwise, the schema is loaded. An error code is returned. */ static int sqlite3ReadSchema( Parse pParse ) { int rc = SQLITE_OK; sqlite3 db = pParse.db; Debug.Assert( sqlite3_mutex_held( db.mutex ) ); if ( 0 == db.init.busy ) { rc = sqlite3Init( db, ref pParse.zErrMsg ); } if ( rc != SQLITE_OK ) { pParse.rc = rc; pParse.nErr++; } return rc; } /* ** Check schema cookies in all databases. If any cookie is out ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies ** make no changes to pParse->rc. */ static void schemaIsValid( Parse pParse ) { sqlite3 db = pParse.db; int iDb; int rc; u32 cookie = 0; Debug.Assert( pParse.checkSchema != 0 ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); for ( iDb = 0; iDb < db.nDb; iDb++ ) { int openedTransaction = 0; /* True if a transaction is opened */ Btree pBt = db.aDb[iDb].pBt; /* Btree database to read cookie from */ if ( pBt == null ) continue; /* If there is not already a read-only (or read-write) transaction opened ** on the b-tree database, open one now. If a transaction is opened, it ** will be closed immediately after reading the meta-value. */ if ( !sqlite3BtreeIsInReadTrans( pBt ) ) { rc = sqlite3BtreeBeginTrans( pBt, 0 ); //if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM ) //{ // db.mallocFailed = 1; //} if ( rc != SQLITE_OK ) return; openedTransaction = 1; } /* Read the schema cookie from the database. If it does not match the ** value stored as part of the in-memory schema representation, ** set Parse.rc to SQLITE_SCHEMA. */ sqlite3BtreeGetMeta( pBt, BTREE_SCHEMA_VERSION, ref cookie ); Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); if ( cookie != db.aDb[iDb].pSchema.schema_cookie ) { sqlite3ResetInternalSchema( db, iDb ); pParse.rc = SQLITE_SCHEMA; } /* Close the transaction, if one was opened. */ if ( openedTransaction != 0 ) { sqlite3BtreeCommit( pBt ); } } } /* ** Convert a schema pointer into the iDb index that indicates ** which database file in db.aDb[] the schema refers to. ** ** If the same database is attached more than once, the first ** attached database is returned. */ static int sqlite3SchemaToIndex( sqlite3 db, Schema pSchema ) { int i = -1000000; /* If pSchema is NULL, then return -1000000. This happens when code in ** expr.c is trying to resolve a reference to a transient table (i.e. one ** created by a sub-select). In this case the return value of this ** function should never be used. ** ** We return -1000000 instead of the more usual -1 simply because using ** -1000000 as the incorrect index into db->aDb[] is much ** more likely to cause a segfault than -1 (of course there are assert() ** statements too, but it never hurts to play the odds). */ Debug.Assert( sqlite3_mutex_held( db.mutex ) ); if ( pSchema != null ) { for ( i = 0; ALWAYS( i < db.nDb ); i++ ) { if ( db.aDb[i].pSchema == pSchema ) { break; } } Debug.Assert( i >= 0 && i < db.nDb ); } return i; } /* ** Compile the UTF-8 encoded SQL statement zSql into a statement handle. */ static int sqlite3Prepare( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ Vdbe pReprepare, /* VM being reprepared */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { Parse pParse; /* Parsing context */ string zErrMsg = ""; /* Error message */ int rc = SQLITE_OK; /* Result code */ int i; /* Loop counter */ /* Allocate the parsing context */ pParse = new Parse();//sqlite3StackAllocZero(db, sizeof(*pParse)); if ( pParse == null ) { rc = SQLITE_NOMEM; goto end_prepare; } pParse.pReprepare = pReprepare; pParse.sLastToken.z = ""; Debug.Assert( ppStmt == null );// assert( ppStmt && *ppStmt==0 ); //Debug.Assert( 0 == db.mallocFailed ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); /* Check to verify that it is possible to get a read lock on all ** database schemas. The inability to get a read lock indicates that ** some other database connection is holding a write-lock, which in ** turn means that the other connection has made uncommitted changes ** to the schema. ** ** Were we to proceed and prepare the statement against the uncommitted ** schema changes and if those schema changes are subsequently rolled ** back and different changes are made in their place, then when this ** prepared statement goes to run the schema cookie would fail to detect ** the schema change. Disaster would follow. ** ** This thread is currently holding mutexes on all Btrees (because ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it ** is not possible for another thread to start a new schema change ** while this routine is running. Hence, we do not need to hold ** locks on the schema, we just need to make sure nobody else is ** holding them. ** ** Note that setting READ_UNCOMMITTED overrides most lock detection, ** but it does *not* override schema lock detection, so this all still ** works even if READ_UNCOMMITTED is set. */ for ( i = 0; i < db.nDb; i++ ) { Btree pBt = db.aDb[i].pBt; if ( pBt != null ) { Debug.Assert( sqlite3BtreeHoldsMutex( pBt ) ); rc = sqlite3BtreeSchemaLocked( pBt ); if ( rc != 0 ) { string zDb = db.aDb[i].zName; sqlite3Error( db, rc, "database schema is locked: %s", zDb ); testcase( db.flags & SQLITE_ReadUncommitted ); goto end_prepare; } } } sqlite3VtabUnlockList( db ); pParse.db = db; pParse.nQueryLoop = (double)1; if ( nBytes >= 0 && ( nBytes == 0 || zSql[nBytes - 1] != 0 ) ) { string zSqlCopy; int mxLen = db.aLimit[SQLITE_LIMIT_SQL_LENGTH]; testcase( nBytes == mxLen ); testcase( nBytes == mxLen + 1 ); if ( nBytes > mxLen ) { sqlite3Error( db, SQLITE_TOOBIG, "statement too long" ); rc = sqlite3ApiExit( db, SQLITE_TOOBIG ); goto end_prepare; } zSqlCopy = zSql.Substring( 0, nBytes );// sqlite3DbStrNDup(db, zSql, nBytes); if ( zSqlCopy != null ) { sqlite3RunParser( pParse, zSqlCopy, ref zErrMsg ); sqlite3DbFree( db, ref zSqlCopy ); //pParse->zTail = &zSql[pParse->zTail-zSqlCopy]; } else { //pParse->zTail = &zSql[nBytes]; } } else { sqlite3RunParser( pParse, zSql, ref zErrMsg ); } Debug.Assert( 1 == (int)pParse.nQueryLoop ); //if ( db.mallocFailed != 0 ) //{ // pParse.rc = SQLITE_NOMEM; //} if ( pParse.rc == SQLITE_DONE ) pParse.rc = SQLITE_OK; if ( pParse.checkSchema != 0 ) { schemaIsValid( pParse ); } //if ( db.mallocFailed != 0 ) //{ // pParse.rc = SQLITE_NOMEM; //} //if (pzTail != null) { pzTail = pParse.zTail == null ? "" : pParse.zTail.ToString(); } rc = pParse.rc; #if !SQLITE_OMIT_EXPLAIN if ( rc == SQLITE_OK && pParse.pVdbe != null && pParse.explain != 0 ) { string[] azColName = new string[] { "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", "selectid", "order", "from", "detail" }; int iFirst, mx; if ( pParse.explain == 2 ) { sqlite3VdbeSetNumCols( pParse.pVdbe, 4 ); iFirst = 8; mx = 12; } else { sqlite3VdbeSetNumCols( pParse.pVdbe, 8 ); iFirst = 0; mx = 8; } for ( i = iFirst; i < mx; i++ ) { sqlite3VdbeSetColName( pParse.pVdbe, i - iFirst, COLNAME_NAME, azColName[i], SQLITE_STATIC ); } } #endif Debug.Assert( db.init.busy == 0 || saveSqlFlag == 0 ); if ( db.init.busy == 0 ) { Vdbe pVdbe = pParse.pVdbe; sqlite3VdbeSetSql( pVdbe, zSql, (int)( zSql.Length - ( pParse.zTail == null ? 0 : pParse.zTail.Length ) ), saveSqlFlag ); } if ( pParse.pVdbe != null && ( rc != SQLITE_OK /*|| db.mallocFailed != 0 */ ) ) { sqlite3VdbeFinalize( pParse.pVdbe ); Debug.Assert( ppStmt == null ); } else { ppStmt = pParse.pVdbe; } if ( zErrMsg != "" ) { sqlite3Error( db, rc, "%s", zErrMsg ); sqlite3DbFree( db, ref zErrMsg ); } else { sqlite3Error( db, rc, 0 ); } /* Delete any TriggerPrg structures allocated while parsing this statement. */ while ( pParse.pTriggerPrg != null ) { TriggerPrg pT = pParse.pTriggerPrg; pParse.pTriggerPrg = pT.pNext; sqlite3DbFree( db, ref pT ); } end_prepare: //sqlite3StackFree( db, pParse ); rc = sqlite3ApiExit( db, rc ); Debug.Assert( ( rc & db.errMask ) == rc ); return rc; } static int sqlite3LockAndPrepare( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ Vdbe pOld, /* VM being reprepared */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; // assert( ppStmt!=0 ); ppStmt = null; if ( !sqlite3SafetyCheckOk( db ) ) { return SQLITE_MISUSE_BKPT(); } sqlite3_mutex_enter( db.mutex ); sqlite3BtreeEnterAll( db ); rc = sqlite3Prepare( db, zSql, nBytes, saveSqlFlag, pOld, ref ppStmt, ref pzTail ); if ( rc == SQLITE_SCHEMA ) { sqlite3_finalize( ppStmt ); rc = sqlite3Prepare( db, zSql, nBytes, saveSqlFlag, pOld, ref ppStmt, ref pzTail ); } sqlite3BtreeLeaveAll( db ); sqlite3_mutex_leave( db.mutex ); return rc; } /* ** Rerun the compilation of a statement after a schema change. ** ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise, ** if the statement cannot be recompiled because another connection has ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error ** occurs, return SQLITE_SCHEMA. */ static int sqlite3Reprepare( Vdbe p ) { int rc; sqlite3_stmt pNew = new sqlite3_stmt(); string zSql; sqlite3 db; Debug.Assert( sqlite3_mutex_held( sqlite3VdbeDb( p ).mutex ) ); zSql = sqlite3_sql( (sqlite3_stmt)p ); Debug.Assert( zSql != null ); /* Reprepare only called for prepare_v2() statements */ db = sqlite3VdbeDb( p ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); string dummy = ""; rc = sqlite3LockAndPrepare( db, zSql, -1, 0, p, ref pNew, ref dummy ); if ( rc != 0 ) { if ( rc == SQLITE_NOMEM ) { // db.mallocFailed = 1; } Debug.Assert( pNew == null ); return rc; } else { Debug.Assert( pNew != null ); } sqlite3VdbeSwap( (Vdbe)pNew, p ); sqlite3TransferBindings( pNew, (sqlite3_stmt)p ); sqlite3VdbeResetStepResult( (Vdbe)pNew ); sqlite3VdbeFinalize( (Vdbe)pNew ); return SQLITE_OK; } /* ** Two versions of the official API. Legacy and new use. In the legacy ** version, the original SQL text is not saved in the prepared statement ** and so if a schema change occurs, SQLITE_SCHEMA is returned by ** sqlite3_step(). In the new version, the original SQL text is retained ** and the statement is automatically recompiled if an schema change ** occurs. */ static public int sqlite3_prepare( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; rc = sqlite3LockAndPrepare( db, zSql, nBytes, 0, null, ref ppStmt, ref pzTail ); Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */ return rc; } public static int sqlite3_prepare_v2( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ int dummy /* ( No string passed) */ ) { string pzTail = null; int rc; rc = sqlite3LockAndPrepare( db, zSql, nBytes, 1, null, ref ppStmt, ref pzTail ); Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */ return rc; } public static int sqlite3_prepare_v2( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; rc = sqlite3LockAndPrepare( db, zSql, nBytes, 1, null, ref ppStmt, ref pzTail ); Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */ return rc; } #if ! SQLITE_OMIT_UTF16 /* ** Compile the UTF-16 encoded SQL statement zSql into a statement handle. */ static int sqlite3Prepare16( sqlite3 db, /* Database handle. */ string zSql, /* UTF-15 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ bool saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ){ /* This function currently works by first transforming the UTF-16 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The ** tricky bit is figuring out the pointer to return in pzTail. */ string zSql8; string zTail8 = ""; int rc = SQLITE_OK; assert( ppStmt ); *ppStmt = 0; if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } sqlite3_mutex_enter(db.mutex); zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE); if( zSql8 !=""){ rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, null, ref ppStmt, ref zTail8); } if( zTail8 !="" && pzTail !=""){ /* If sqlite3_prepare returns a tail pointer, we calculate the ** equivalent pointer into the UTF-16 string by counting the unicode ** characters between zSql8 and zTail8, and then returning a pointer ** the same number of characters into the UTF-16 string. */ Debugger.Break (); // TODO -- // int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8)); // pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed); } sqlite3DbFree(db,ref zSql8); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db.mutex); return rc; } /* ** Two versions of the official API. Legacy and new use. In the legacy ** version, the original SQL text is not saved in the prepared statement ** and so if a schema change occurs, SQLITE_SCHEMA is returned by ** sqlite3_step(). In the new version, the original SQL text is retained ** and the statement is automatically recompiled if an schema change ** occurs. */ public static int sqlite3_prepare16( sqlite3 db, /* Database handle. */ string zSql, /* UTF-16 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ){ int rc; rc = sqlite3Prepare16(db,zSql,nBytes,false,ref ppStmt,ref pzTail); Debug.Assert( rc==SQLITE_OK || ppStmt==null || ppStmt==null ); /* VERIFY: F13021 */ return rc; } public static int sqlite3_prepare16_v2( sqlite3 db, /* Database handle. */ string zSql, /* UTF-16 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; rc = sqlite3Prepare16(db,zSql,nBytes,true,ref ppStmt,ref pzTail); Debug.Assert( rc==SQLITE_OK || ppStmt==null || ppStmt==null ); /* VERIFY: F13021 */ return rc; } #endif // * SQLITE_OMIT_UTF16 */ } }
/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2021 Cedric Coste Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Web.UI; using Newtonsoft.Json; using Myrtille.Services.Contracts; namespace Myrtille.Web { public partial class SendInputs : Page { /// <summary> /// send user input(s) (mouse, keyboard) to the remote session /// if long-polling is disabled (xhr only), also returns image data within the response /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load( object sender, EventArgs e) { // if cookies are enabled, the http session id is added to the http request headers; otherwise, it's added to the http request url // in both cases, the given http session is automatically bound to the current http context RemoteSession remoteSession = null; try { if (Session[HttpSessionStateVariables.RemoteSession.ToString()] == null) throw new NullReferenceException(); // retrieve the remote session for the current http session remoteSession = (RemoteSession)Session[HttpSessionStateVariables.RemoteSession.ToString()]; var clientId = Request.QueryString["clientId"]; if (!remoteSession.Manager.Clients.ContainsKey(clientId)) { lock (remoteSession.Manager.ClientsLock) { remoteSession.Manager.Clients.Add(clientId, new RemoteSessionClient(clientId)); } } var client = remoteSession.Manager.Clients[clientId]; // filters out the dummy xhr calls (used with websocket to keep the http session alive) if (!string.IsNullOrEmpty(Request.QueryString["data"])) { lock (client.Lock) { // register a message queue for the client (now using HTML4) if (client.MessageQueue == null) { client.MessageQueue = new List<RemoteSessionMessage>(); } } // update guest information if (!Session.SessionID.Equals(remoteSession.OwnerSessionID)) { if (Session[HttpSessionStateVariables.GuestInfo.ToString()] != null) { ((GuestInfo)Session[HttpSessionStateVariables.GuestInfo.ToString()]).Websocket = false; } } // connect the remote server else if (remoteSession.State == RemoteSessionState.Connecting && !remoteSession.Manager.HostClient.ProcessStarted) { try { // create pipes for the web gateway and the host client to talk remoteSession.Manager.Pipes.CreatePipes(); // the host client does connect the pipes when it starts; when it stops (either because it was closed, crashed or because the remote session had ended), pipes are released // as the process command line can be displayed into the task manager / process explorer, the connection settings (including user credentials) are now passed to the host client through the inputs pipe // use http://technet.microsoft.com/en-us/sysinternals/dd581625 to track the existing pipes remoteSession.Manager.HostClient.StartProcess( remoteSession.Id, remoteSession.HostType, remoteSession.SecurityProtocol, remoteSession.ServerAddress, remoteSession.VMGuid, remoteSession.UserDomain, remoteSession.UserName, remoteSession.StartProgram, remoteSession.ClientWidth, remoteSession.ClientHeight, remoteSession.AllowRemoteClipboard, remoteSession.AllowPrintDownload, remoteSession.AllowAudioPlayback); } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to connect the remote session {0} ({1})", remoteSession.Id, exc); throw; } } } try { // retrieve params var data = Request.QueryString["data"]; var imgIdx = int.Parse(Request.QueryString["imgIdx"]); var latency = int.Parse(Request.QueryString["latency"]); var imgReturn = int.Parse(Request.QueryString["imgReturn"]) == 1; // process input(s) if (!string.IsNullOrEmpty(data)) { remoteSession.Manager.ProcessInputs(Session, clientId, data); } client.ImgIdx = imgIdx; client.Latency = latency; // xhr only if (imgReturn) { // concatenate text for terminal output to avoid a slow rendering // if another message type is in the queue, it will be given priority over the terminal // the terminal is refreshed often, so it shouldn't be an issue... var msgText = string.Empty; var msgComplete = false; if (client.MessageQueue != null) { while (client.MessageQueue.Count > 0 && !msgComplete) { var message = client.MessageQueue[0]; switch (message.Type) { case MessageType.TerminalOutput: msgText += message.Text; break; default: msgText = JsonConvert.SerializeObject(message); msgComplete = true; break; } lock (((ICollection)client.MessageQueue).SyncRoot) { client.MessageQueue.RemoveAt(0); } } } // message if (!string.IsNullOrEmpty(msgText)) { if (!msgComplete) { Response.Write(JsonConvert.SerializeObject(new RemoteSessionMessage { Type = MessageType.TerminalOutput, Text = msgText })); } else { Response.Write(msgText); } } // image else { var image = remoteSession.Manager.GetNextUpdate(imgIdx); if (image != null) { System.Diagnostics.Trace.TraceInformation("Returning image {0} ({1}), client {2}, remote session {3}", image.Idx, (image.Fullscreen ? "screen" : "region"), clientId, remoteSession.Id); var imgData = image.Idx + "," + image.PosX + "," + image.PosY + "," + image.Width + "," + image.Height + "," + image.Format.ToString().ToLower() + "," + image.Quality + "," + image.Fullscreen.ToString().ToLower() + "," + Convert.ToBase64String(image.Data); // write the output Response.Write(imgData); } } } } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to send user input(s), client {0}, remote session {1} ({2})", clientId, remoteSession.Id, exc); } } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to retrieve the active remote session ({0})", exc); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; internal class TestApp { private static byte test_0_0(byte num, AA init, AA zero) { return init.q; } private static byte test_0_1(byte num, AA init, AA zero) { zero.q = num; return zero.q; } private static byte test_0_2(byte num, AA init, AA zero) { return (byte)(init.q + zero.q); } private static byte test_0_3(byte num, AA init, AA zero) { return (byte)checked(init.q - zero.q); } private static byte test_0_4(byte num, AA init, AA zero) { zero.q += num; return zero.q; } private static byte test_0_5(byte num, AA init, AA zero) { zero.q += init.q; return zero.q; } private static byte test_0_6(byte num, AA init, AA zero) { if (init.q == num) return 100; else return zero.q; } private static byte test_0_7(byte num, AA init, AA zero) { return (byte)(init.q < num + 1 ? 100 : -1); } private static byte test_0_8(byte num, AA init, AA zero) { return (byte)((init.q > zero.q ? 1 : 0) + 99); } private static byte test_0_9(byte num, AA init, AA zero) { return (byte)((init.q ^ zero.q) | num); } private static byte test_0_10(byte num, AA init, AA zero) { zero.q |= init.q; return (byte)(zero.q & num); } private static byte test_0_11(byte num, AA init, AA zero) { return (byte)(init.q >> zero.q); } private static byte test_0_12(byte num, AA init, AA zero) { return AA.a_init[init.q].q; } private static byte test_0_13(byte num, AA init, AA zero) { return AA.aa_init[num - 100, (init.q | 1) - 2, 1 + zero.q].q; } private static byte test_0_14(byte num, AA init, AA zero) { object bb = init.q; return (byte)bb; } private static byte test_0_15(byte num, AA init, AA zero) { double dbl = init.q; return (byte)dbl; } private static byte test_0_16(byte num, AA init, AA zero) { return AA.call_target(init.q); } private static byte test_0_17(byte num, AA init, AA zero) { return AA.call_target_ref(ref init.q); } private static byte test_1_0(byte num, ref AA r_init, ref AA r_zero) { return r_init.q; } private static byte test_1_1(byte num, ref AA r_init, ref AA r_zero) { r_zero.q = num; return r_zero.q; } private static byte test_1_2(byte num, ref AA r_init, ref AA r_zero) { return (byte)(r_init.q + r_zero.q); } private static byte test_1_3(byte num, ref AA r_init, ref AA r_zero) { return (byte)checked(r_init.q - r_zero.q); } private static byte test_1_4(byte num, ref AA r_init, ref AA r_zero) { r_zero.q += num; return r_zero.q; } private static byte test_1_5(byte num, ref AA r_init, ref AA r_zero) { r_zero.q += r_init.q; return r_zero.q; } private static byte test_1_6(byte num, ref AA r_init, ref AA r_zero) { if (r_init.q == num) return 100; else return r_zero.q; } private static byte test_1_7(byte num, ref AA r_init, ref AA r_zero) { return (byte)(r_init.q < num + 1 ? 100 : -1); } private static byte test_1_8(byte num, ref AA r_init, ref AA r_zero) { return (byte)((r_init.q > r_zero.q ? 1 : 0) + 99); } private static byte test_1_9(byte num, ref AA r_init, ref AA r_zero) { return (byte)((r_init.q ^ r_zero.q) | num); } private static byte test_1_10(byte num, ref AA r_init, ref AA r_zero) { r_zero.q |= r_init.q; return (byte)(r_zero.q & num); } private static byte test_1_11(byte num, ref AA r_init, ref AA r_zero) { return (byte)(r_init.q >> r_zero.q); } private static byte test_1_12(byte num, ref AA r_init, ref AA r_zero) { return AA.a_init[r_init.q].q; } private static byte test_1_13(byte num, ref AA r_init, ref AA r_zero) { return AA.aa_init[num - 100, (r_init.q | 1) - 2, 1 + r_zero.q].q; } private static byte test_1_14(byte num, ref AA r_init, ref AA r_zero) { object bb = r_init.q; return (byte)bb; } private static byte test_1_15(byte num, ref AA r_init, ref AA r_zero) { double dbl = r_init.q; return (byte)dbl; } private static byte test_1_16(byte num, ref AA r_init, ref AA r_zero) { return AA.call_target(r_init.q); } private static byte test_1_17(byte num, ref AA r_init, ref AA r_zero) { return AA.call_target_ref(ref r_init.q); } private static byte test_2_0(byte num) { return AA.a_init[num].q; } private static byte test_2_1(byte num) { AA.a_zero[num].q = num; return AA.a_zero[num].q; } private static byte test_2_2(byte num) { return (byte)(AA.a_init[num].q + AA.a_zero[num].q); } private static byte test_2_3(byte num) { return (byte)checked(AA.a_init[num].q - AA.a_zero[num].q); } private static byte test_2_4(byte num) { AA.a_zero[num].q += num; return AA.a_zero[num].q; } private static byte test_2_5(byte num) { AA.a_zero[num].q += AA.a_init[num].q; return AA.a_zero[num].q; } private static byte test_2_6(byte num) { if (AA.a_init[num].q == num) return 100; else return AA.a_zero[num].q; } private static byte test_2_7(byte num) { return (byte)(AA.a_init[num].q < num + 1 ? 100 : -1); } private static byte test_2_8(byte num) { return (byte)((AA.a_init[num].q > AA.a_zero[num].q ? 1 : 0) + 99); } private static byte test_2_9(byte num) { return (byte)((AA.a_init[num].q ^ AA.a_zero[num].q) | num); } private static byte test_2_10(byte num) { AA.a_zero[num].q |= AA.a_init[num].q; return (byte)(AA.a_zero[num].q & num); } private static byte test_2_11(byte num) { return (byte)(AA.a_init[num].q >> AA.a_zero[num].q); } private static byte test_2_12(byte num) { return AA.a_init[AA.a_init[num].q].q; } private static byte test_2_13(byte num) { return AA.aa_init[num - 100, (AA.a_init[num].q | 1) - 2, 1 + AA.a_zero[num].q].q; } private static byte test_2_14(byte num) { object bb = AA.a_init[num].q; return (byte)bb; } private static byte test_2_15(byte num) { double dbl = AA.a_init[num].q; return (byte)dbl; } private static byte test_2_16(byte num) { return AA.call_target(AA.a_init[num].q); } private static byte test_2_17(byte num) { return AA.call_target_ref(ref AA.a_init[num].q); } private static byte test_3_0(byte num) { return AA.aa_init[0, num - 1, num / 100].q; } private static byte test_3_1(byte num) { AA.aa_zero[0, num - 1, num / 100].q = num; return AA.aa_zero[0, num - 1, num / 100].q; } private static byte test_3_2(byte num) { return (byte)(AA.aa_init[0, num - 1, num / 100].q + AA.aa_zero[0, num - 1, num / 100].q); } private static byte test_3_3(byte num) { return (byte)checked(AA.aa_init[0, num - 1, num / 100].q - AA.aa_zero[0, num - 1, num / 100].q); } private static byte test_3_4(byte num) { AA.aa_zero[0, num - 1, num / 100].q += num; return AA.aa_zero[0, num - 1, num / 100].q; } private static byte test_3_5(byte num) { AA.aa_zero[0, num - 1, num / 100].q += AA.aa_init[0, num - 1, num / 100].q; return AA.aa_zero[0, num - 1, num / 100].q; } private static byte test_3_6(byte num) { if (AA.aa_init[0, num - 1, num / 100].q == num) return 100; else return AA.aa_zero[0, num - 1, num / 100].q; } private static byte test_3_7(byte num) { return (byte)(AA.aa_init[0, num - 1, num / 100].q < num + 1 ? 100 : -1); } private static byte test_3_8(byte num) { return (byte)((AA.aa_init[0, num - 1, num / 100].q > AA.aa_zero[0, num - 1, num / 100].q ? 1 : 0) + 99); } private static byte test_3_9(byte num) { return (byte)((AA.aa_init[0, num - 1, num / 100].q ^ AA.aa_zero[0, num - 1, num / 100].q) | num); } private static byte test_3_10(byte num) { AA.aa_zero[0, num - 1, num / 100].q |= AA.aa_init[0, num - 1, num / 100].q; return (byte)(AA.aa_zero[0, num - 1, num / 100].q & num); } private static byte test_3_11(byte num) { return (byte)(AA.aa_init[0, num - 1, num / 100].q >> AA.aa_zero[0, num - 1, num / 100].q); } private static byte test_3_12(byte num) { return AA.a_init[AA.aa_init[0, num - 1, num / 100].q].q; } private static byte test_3_13(byte num) { return AA.aa_init[num - 100, (AA.aa_init[0, num - 1, num / 100].q | 1) - 2, 1 + AA.aa_zero[0, num - 1, num / 100].q].q; } private static byte test_3_14(byte num) { object bb = AA.aa_init[0, num - 1, num / 100].q; return (byte)bb; } private static byte test_3_15(byte num) { double dbl = AA.aa_init[0, num - 1, num / 100].q; return (byte)dbl; } private static byte test_3_16(byte num) { return AA.call_target(AA.aa_init[0, num - 1, num / 100].q); } private static byte test_3_17(byte num) { return AA.call_target_ref(ref AA.aa_init[0, num - 1, num / 100].q); } private static byte test_4_0(byte num) { return BB.f_init.q; } private static byte test_4_1(byte num) { BB.f_zero.q = num; return BB.f_zero.q; } private static byte test_4_2(byte num) { return (byte)(BB.f_init.q + BB.f_zero.q); } private static byte test_4_3(byte num) { return (byte)checked(BB.f_init.q - BB.f_zero.q); } private static byte test_4_4(byte num) { BB.f_zero.q += num; return BB.f_zero.q; } private static byte test_4_5(byte num) { BB.f_zero.q += BB.f_init.q; return BB.f_zero.q; } private static byte test_4_6(byte num) { if (BB.f_init.q == num) return 100; else return BB.f_zero.q; } private static byte test_4_7(byte num) { return (byte)(BB.f_init.q < num + 1 ? 100 : -1); } private static byte test_4_8(byte num) { return (byte)((BB.f_init.q > BB.f_zero.q ? 1 : 0) + 99); } private static byte test_4_9(byte num) { return (byte)((BB.f_init.q ^ BB.f_zero.q) | num); } private static byte test_4_10(byte num) { BB.f_zero.q |= BB.f_init.q; return (byte)(BB.f_zero.q & num); } private static byte test_4_11(byte num) { return (byte)(BB.f_init.q >> BB.f_zero.q); } private static byte test_4_12(byte num) { return AA.a_init[BB.f_init.q].q; } private static byte test_4_13(byte num) { return AA.aa_init[num - 100, (BB.f_init.q | 1) - 2, 1 + BB.f_zero.q].q; } private static byte test_4_14(byte num) { object bb = BB.f_init.q; return (byte)bb; } private static byte test_4_15(byte num) { double dbl = BB.f_init.q; return (byte)dbl; } private static byte test_4_16(byte num) { return AA.call_target(BB.f_init.q); } private static byte test_4_17(byte num) { return AA.call_target_ref(ref BB.f_init.q); } private static byte test_5_0(byte num) { return ((AA)AA.b_init).q; } private static byte test_6_0(byte num, TypedReference tr_init) { return __refvalue(tr_init, AA).q; } private static unsafe byte test_7_0(byte num, void* ptr_init, void* ptr_zero) { return (*((AA*)ptr_init)).q; } private static unsafe byte test_7_1(byte num, void* ptr_init, void* ptr_zero) { (*((AA*)ptr_zero)).q = num; return (*((AA*)ptr_zero)).q; } private static unsafe byte test_7_2(byte num, void* ptr_init, void* ptr_zero) { return (byte)((*((AA*)ptr_init)).q + (*((AA*)ptr_zero)).q); } private static unsafe byte test_7_3(byte num, void* ptr_init, void* ptr_zero) { return (byte)checked((*((AA*)ptr_init)).q - (*((AA*)ptr_zero)).q); } private static unsafe byte test_7_4(byte num, void* ptr_init, void* ptr_zero) { (*((AA*)ptr_zero)).q += num; return (*((AA*)ptr_zero)).q; } private static unsafe byte test_7_5(byte num, void* ptr_init, void* ptr_zero) { (*((AA*)ptr_zero)).q += (*((AA*)ptr_init)).q; return (*((AA*)ptr_zero)).q; } private static unsafe byte test_7_6(byte num, void* ptr_init, void* ptr_zero) { if ((*((AA*)ptr_init)).q == num) return 100; else return (*((AA*)ptr_zero)).q; } private static unsafe byte test_7_7(byte num, void* ptr_init, void* ptr_zero) { return (byte)((*((AA*)ptr_init)).q < num + 1 ? 100 : -1); } private static unsafe byte test_7_8(byte num, void* ptr_init, void* ptr_zero) { return (byte)(((*((AA*)ptr_init)).q > (*((AA*)ptr_zero)).q ? 1 : 0) + 99); } private static unsafe byte test_7_9(byte num, void* ptr_init, void* ptr_zero) { return (byte)(((*((AA*)ptr_init)).q ^ (*((AA*)ptr_zero)).q) | num); } private static unsafe byte test_7_10(byte num, void* ptr_init, void* ptr_zero) { (*((AA*)ptr_zero)).q |= (*((AA*)ptr_init)).q; return (byte)((*((AA*)ptr_zero)).q & num); } private static unsafe byte test_7_11(byte num, void* ptr_init, void* ptr_zero) { return (byte)((*((AA*)ptr_init)).q >> (*((AA*)ptr_zero)).q); } private static unsafe byte test_7_12(byte num, void* ptr_init, void* ptr_zero) { return AA.a_init[(*((AA*)ptr_init)).q].q; } private static unsafe byte test_7_13(byte num, void* ptr_init, void* ptr_zero) { return AA.aa_init[num - 100, ((*((AA*)ptr_init)).q | 1) - 2, 1 + (*((AA*)ptr_zero)).q].q; } private static unsafe byte test_7_14(byte num, void* ptr_init, void* ptr_zero) { object bb = (*((AA*)ptr_init)).q; return (byte)bb; } private static unsafe byte test_7_15(byte num, void* ptr_init, void* ptr_zero) { double dbl = (*((AA*)ptr_init)).q; return (byte)dbl; } private static unsafe byte test_7_16(byte num, void* ptr_init, void* ptr_zero) { return AA.call_target((*((AA*)ptr_init)).q); } private static unsafe byte test_7_17(byte num, void* ptr_init, void* ptr_zero) { return AA.call_target_ref(ref (*((AA*)ptr_init)).q); } private static unsafe int Main() { AA.reset(); if (test_0_0(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_0() failed."); return 101; } AA.verify_all(); AA.reset(); if (test_0_1(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_1() failed."); return 102; } AA.verify_all(); AA.reset(); if (test_0_2(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_2() failed."); return 103; } AA.verify_all(); AA.reset(); if (test_0_3(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_3() failed."); return 104; } AA.verify_all(); AA.reset(); if (test_0_4(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_4() failed."); return 105; } AA.verify_all(); AA.reset(); if (test_0_5(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_5() failed."); return 106; } AA.verify_all(); AA.reset(); if (test_0_6(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_6() failed."); return 107; } AA.verify_all(); AA.reset(); if (test_0_7(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_7() failed."); return 108; } AA.verify_all(); AA.reset(); if (test_0_8(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_8() failed."); return 109; } AA.verify_all(); AA.reset(); if (test_0_9(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_9() failed."); return 110; } AA.verify_all(); AA.reset(); if (test_0_10(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_10() failed."); return 111; } AA.verify_all(); AA.reset(); if (test_0_11(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_11() failed."); return 112; } AA.verify_all(); AA.reset(); if (test_0_12(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_12() failed."); return 113; } AA.verify_all(); AA.reset(); if (test_0_13(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_13() failed."); return 114; } AA.verify_all(); AA.reset(); if (test_0_14(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_14() failed."); return 115; } AA.verify_all(); AA.reset(); if (test_0_15(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_15() failed."); return 116; } AA.verify_all(); AA.reset(); if (test_0_16(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_16() failed."); return 117; } AA.verify_all(); AA.reset(); if (test_0_17(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_17() failed."); return 118; } AA.verify_all(); AA.reset(); if (test_1_0(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_0() failed."); return 119; } AA.verify_all(); AA.reset(); if (test_1_1(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_1() failed."); return 120; } AA.verify_all(); AA.reset(); if (test_1_2(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_2() failed."); return 121; } AA.verify_all(); AA.reset(); if (test_1_3(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_3() failed."); return 122; } AA.verify_all(); AA.reset(); if (test_1_4(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_4() failed."); return 123; } AA.verify_all(); AA.reset(); if (test_1_5(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_5() failed."); return 124; } AA.verify_all(); AA.reset(); if (test_1_6(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_6() failed."); return 125; } AA.verify_all(); AA.reset(); if (test_1_7(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_7() failed."); return 126; } AA.verify_all(); AA.reset(); if (test_1_8(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_8() failed."); return 127; } AA.verify_all(); AA.reset(); if (test_1_9(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_9() failed."); return 128; } AA.verify_all(); AA.reset(); if (test_1_10(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_10() failed."); return 129; } AA.verify_all(); AA.reset(); if (test_1_11(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_11() failed."); return 130; } AA.verify_all(); AA.reset(); if (test_1_12(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_12() failed."); return 131; } AA.verify_all(); AA.reset(); if (test_1_13(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_13() failed."); return 132; } AA.verify_all(); AA.reset(); if (test_1_14(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_14() failed."); return 133; } AA.verify_all(); AA.reset(); if (test_1_15(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_15() failed."); return 134; } AA.verify_all(); AA.reset(); if (test_1_16(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_16() failed."); return 135; } AA.verify_all(); AA.reset(); if (test_1_17(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_17() failed."); return 136; } AA.verify_all(); AA.reset(); if (test_2_0(100) != 100) { Console.WriteLine("test_2_0() failed."); return 137; } AA.verify_all(); AA.reset(); if (test_2_1(100) != 100) { Console.WriteLine("test_2_1() failed."); return 138; } AA.verify_all(); AA.reset(); if (test_2_2(100) != 100) { Console.WriteLine("test_2_2() failed."); return 139; } AA.verify_all(); AA.reset(); if (test_2_3(100) != 100) { Console.WriteLine("test_2_3() failed."); return 140; } AA.verify_all(); AA.reset(); if (test_2_4(100) != 100) { Console.WriteLine("test_2_4() failed."); return 141; } AA.verify_all(); AA.reset(); if (test_2_5(100) != 100) { Console.WriteLine("test_2_5() failed."); return 142; } AA.verify_all(); AA.reset(); if (test_2_6(100) != 100) { Console.WriteLine("test_2_6() failed."); return 143; } AA.verify_all(); AA.reset(); if (test_2_7(100) != 100) { Console.WriteLine("test_2_7() failed."); return 144; } AA.verify_all(); AA.reset(); if (test_2_8(100) != 100) { Console.WriteLine("test_2_8() failed."); return 145; } AA.verify_all(); AA.reset(); if (test_2_9(100) != 100) { Console.WriteLine("test_2_9() failed."); return 146; } AA.verify_all(); AA.reset(); if (test_2_10(100) != 100) { Console.WriteLine("test_2_10() failed."); return 147; } AA.verify_all(); AA.reset(); if (test_2_11(100) != 100) { Console.WriteLine("test_2_11() failed."); return 148; } AA.verify_all(); AA.reset(); if (test_2_12(100) != 100) { Console.WriteLine("test_2_12() failed."); return 149; } AA.verify_all(); AA.reset(); if (test_2_13(100) != 100) { Console.WriteLine("test_2_13() failed."); return 150; } AA.verify_all(); AA.reset(); if (test_2_14(100) != 100) { Console.WriteLine("test_2_14() failed."); return 151; } AA.verify_all(); AA.reset(); if (test_2_15(100) != 100) { Console.WriteLine("test_2_15() failed."); return 152; } AA.verify_all(); AA.reset(); if (test_2_16(100) != 100) { Console.WriteLine("test_2_16() failed."); return 153; } AA.verify_all(); AA.reset(); if (test_2_17(100) != 100) { Console.WriteLine("test_2_17() failed."); return 154; } AA.verify_all(); AA.reset(); if (test_3_0(100) != 100) { Console.WriteLine("test_3_0() failed."); return 155; } AA.verify_all(); AA.reset(); if (test_3_1(100) != 100) { Console.WriteLine("test_3_1() failed."); return 156; } AA.verify_all(); AA.reset(); if (test_3_2(100) != 100) { Console.WriteLine("test_3_2() failed."); return 157; } AA.verify_all(); AA.reset(); if (test_3_3(100) != 100) { Console.WriteLine("test_3_3() failed."); return 158; } AA.verify_all(); AA.reset(); if (test_3_4(100) != 100) { Console.WriteLine("test_3_4() failed."); return 159; } AA.verify_all(); AA.reset(); if (test_3_5(100) != 100) { Console.WriteLine("test_3_5() failed."); return 160; } AA.verify_all(); AA.reset(); if (test_3_6(100) != 100) { Console.WriteLine("test_3_6() failed."); return 161; } AA.verify_all(); AA.reset(); if (test_3_7(100) != 100) { Console.WriteLine("test_3_7() failed."); return 162; } AA.verify_all(); AA.reset(); if (test_3_8(100) != 100) { Console.WriteLine("test_3_8() failed."); return 163; } AA.verify_all(); AA.reset(); if (test_3_9(100) != 100) { Console.WriteLine("test_3_9() failed."); return 164; } AA.verify_all(); AA.reset(); if (test_3_10(100) != 100) { Console.WriteLine("test_3_10() failed."); return 165; } AA.verify_all(); AA.reset(); if (test_3_11(100) != 100) { Console.WriteLine("test_3_11() failed."); return 166; } AA.verify_all(); AA.reset(); if (test_3_12(100) != 100) { Console.WriteLine("test_3_12() failed."); return 167; } AA.verify_all(); AA.reset(); if (test_3_13(100) != 100) { Console.WriteLine("test_3_13() failed."); return 168; } AA.verify_all(); AA.reset(); if (test_3_14(100) != 100) { Console.WriteLine("test_3_14() failed."); return 169; } AA.verify_all(); AA.reset(); if (test_3_15(100) != 100) { Console.WriteLine("test_3_15() failed."); return 170; } AA.verify_all(); AA.reset(); if (test_3_16(100) != 100) { Console.WriteLine("test_3_16() failed."); return 171; } AA.verify_all(); AA.reset(); if (test_3_17(100) != 100) { Console.WriteLine("test_3_17() failed."); return 172; } AA.verify_all(); AA.reset(); if (test_4_0(100) != 100) { Console.WriteLine("test_4_0() failed."); return 173; } AA.verify_all(); AA.reset(); if (test_4_1(100) != 100) { Console.WriteLine("test_4_1() failed."); return 174; } AA.verify_all(); AA.reset(); if (test_4_2(100) != 100) { Console.WriteLine("test_4_2() failed."); return 175; } AA.verify_all(); AA.reset(); if (test_4_3(100) != 100) { Console.WriteLine("test_4_3() failed."); return 176; } AA.verify_all(); AA.reset(); if (test_4_4(100) != 100) { Console.WriteLine("test_4_4() failed."); return 177; } AA.verify_all(); AA.reset(); if (test_4_5(100) != 100) { Console.WriteLine("test_4_5() failed."); return 178; } AA.verify_all(); AA.reset(); if (test_4_6(100) != 100) { Console.WriteLine("test_4_6() failed."); return 179; } AA.verify_all(); AA.reset(); if (test_4_7(100) != 100) { Console.WriteLine("test_4_7() failed."); return 180; } AA.verify_all(); AA.reset(); if (test_4_8(100) != 100) { Console.WriteLine("test_4_8() failed."); return 181; } AA.verify_all(); AA.reset(); if (test_4_9(100) != 100) { Console.WriteLine("test_4_9() failed."); return 182; } AA.verify_all(); AA.reset(); if (test_4_10(100) != 100) { Console.WriteLine("test_4_10() failed."); return 183; } AA.verify_all(); AA.reset(); if (test_4_11(100) != 100) { Console.WriteLine("test_4_11() failed."); return 184; } AA.verify_all(); AA.reset(); if (test_4_12(100) != 100) { Console.WriteLine("test_4_12() failed."); return 185; } AA.verify_all(); AA.reset(); if (test_4_13(100) != 100) { Console.WriteLine("test_4_13() failed."); return 186; } AA.verify_all(); AA.reset(); if (test_4_14(100) != 100) { Console.WriteLine("test_4_14() failed."); return 187; } AA.verify_all(); AA.reset(); if (test_4_15(100) != 100) { Console.WriteLine("test_4_15() failed."); return 188; } AA.verify_all(); AA.reset(); if (test_4_16(100) != 100) { Console.WriteLine("test_4_16() failed."); return 189; } AA.verify_all(); AA.reset(); if (test_4_17(100) != 100) { Console.WriteLine("test_4_17() failed."); return 190; } AA.verify_all(); AA.reset(); if (test_5_0(100) != 100) { Console.WriteLine("test_5_0() failed."); return 191; } AA.verify_all(); AA.reset(); if (test_6_0(100, __makeref(AA._init)) != 100) { Console.WriteLine("test_6_0() failed."); return 192; } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_0(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_0() failed."); return 193; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_1(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_1() failed."); return 194; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_2(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_2() failed."); return 195; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_3(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_3() failed."); return 196; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_4(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_4() failed."); return 197; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_5(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_5() failed."); return 198; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_6(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_6() failed."); return 199; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_7(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_7() failed."); return 200; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_8(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_8() failed."); return 201; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_9(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_9() failed."); return 202; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_10(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_10() failed."); return 203; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_11(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_11() failed."); return 204; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_12(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_12() failed."); return 205; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_13(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_13() failed."); return 206; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_14(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_14() failed."); return 207; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_15(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_15() failed."); return 208; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_16(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_16() failed."); return 209; } } AA.verify_all(); AA.reset(); fixed (void* p_init = &AA._init, p_zero = &AA._zero) { if (test_7_17(100, p_init, p_zero) != 100) { Console.WriteLine("test_7_17() failed."); return 210; } } AA.verify_all(); Console.WriteLine("All tests passed."); return 100; } }
using Microsoft.Azure.Commands.Compute.Common; using Microsoft.Azure.Common.Authentication.Models; using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC; using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC.Publish; using Microsoft.WindowsAzure.Storage.Auth; using System; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Extension.DSC { /// <summary> /// Uploads a Desired State Configuration script to Azure blob storage, which /// later can be applied to Azure Virtual Machines using the /// Set-AzureVMDscExtension cmdlet. /// </summary> [Cmdlet( VerbsData.Publish, ProfileNouns.VirtualMachineDscConfiguration, SupportsShouldProcess = true, DefaultParameterSetName = UploadArchiveParameterSetName), OutputType( typeof(String))] public class PublishAzureVMDscConfigurationCommand : DscExtensionPublishCmdletCommonBase { private const string CreateArchiveParameterSetName = "CreateArchive"; private const string UploadArchiveParameterSetName = "UploadArchive"; [Parameter( Mandatory = true, Position = 2, ParameterSetName = UploadArchiveParameterSetName, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the resource group that contains the storage account.")] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } /// <summary> /// Path to a file containing one or more configurations; the file can be a /// PowerShell script (*.ps1) or MOF interface (*.mof). /// </summary> [Parameter( Mandatory = true, Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a file containing one or more configurations")] [ValidateNotNullOrEmpty] public string ConfigurationPath { get; set; } /// <summary> /// Name of the Azure Storage Container the configuration is uploaded to. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, Position = 4, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "Name of the Azure Storage Container the configuration is uploaded to")] [ValidateNotNullOrEmpty] public string ContainerName { get; set; } /// <summary> /// The Azure Storage Account name used to upload the configuration script to the container specified by ContainerName. /// </summary> [Parameter( Mandatory = true, Position = 3, ValueFromPipelineByPropertyName = true, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "The Azure Storage Account name used to upload the configuration script to the container " + "specified by ContainerName ")] [ValidateNotNullOrEmpty] public String StorageAccountName { get; set; } /// <summary> /// Path to a local ZIP file to write the configuration archive to. /// When using this parameter, Publish-AzureVMDscConfiguration creates a /// local ZIP archive instead of uploading it to blob storage.. /// </summary> [Alias("ConfigurationArchivePath")] [Parameter( Position = 2, ValueFromPipelineByPropertyName = true, ParameterSetName = CreateArchiveParameterSetName, HelpMessage = "Path to a local ZIP file to write the configuration archive to.")] [ValidateNotNullOrEmpty] public string OutputArchivePath { get; set; } /// <summary> /// Suffix for the storage end point, e.g. core.windows.net /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "Suffix for the storage end point, e.g. core.windows.net")] [ValidateNotNullOrEmpty] public string StorageEndpointSuffix { get; set; } /// <summary> /// By default Publish-AzureVMDscConfiguration will not overwrite any existing blobs. /// Use -Force to overwrite them. /// </summary> [Parameter(HelpMessage = "By default Publish-AzureVMDscConfiguration will not overwrite any existing blobs")] public SwitchParameter Force { get; set; } /// <summary> /// Excludes DSC resource dependencies from the configuration archive /// </summary> [Parameter(HelpMessage = "Excludes DSC resource dependencies from the configuration archive")] public SwitchParameter SkipDependencyDetection { get; set; } /// <summary> ///Path to a .psd1 file that specifies the data for the Configuration. This /// file must contain a hashtable with the items described in /// http://technet.microsoft.com/en-us/library/dn249925.aspx. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration. This is added to the configuration " + "archive and then passed to the configuration function. It gets overwritten by the configuration data path " + "provided through the Set-AzureVMDscExtension cmdlet")] [ValidateNotNullOrEmpty] public string ConfigurationDataPath { get; set; } /// <summary> /// Path to a file or a directory to include in the configuration archive /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a file or a directory to include in the configuration archive. It gets downloaded to the " + "VM along with the configuration")] [ValidateNotNullOrEmpty] public String[] AdditionalPath { get; set; } //Private Variables /// <summary> /// Credentials used to access Azure Storage /// </summary> private StorageCredentials _storageCredentials; public override void ExecuteCmdlet() { base.ExecuteCmdlet(); try { ValidatePsVersion(); //validate cmdlet params ConfigurationPath = GetUnresolvedProviderPathFromPSPath(ConfigurationPath); ValidateConfigurationPath(ConfigurationPath, ParameterSetName); if (ConfigurationDataPath != null) { ConfigurationDataPath = GetUnresolvedProviderPathFromPSPath(ConfigurationDataPath); ValidateConfigurationDataPath(ConfigurationDataPath); } if (AdditionalPath != null && AdditionalPath.Length > 0) { for (var count = 0; count < AdditionalPath.Length; count++) { AdditionalPath[count] = GetUnresolvedProviderPathFromPSPath(AdditionalPath[count]); } } switch (ParameterSetName) { case CreateArchiveParameterSetName: OutputArchivePath = GetUnresolvedProviderPathFromPSPath(OutputArchivePath); break; case UploadArchiveParameterSetName: _storageCredentials = this.GetStorageCredentials(ResourceGroupName,StorageAccountName); if (ContainerName == null) { ContainerName = DscExtensionCmdletConstants.DefaultContainerName; } if (StorageEndpointSuffix == null) { StorageEndpointSuffix = Profile.Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix); } break; } PublishConfiguration( ConfigurationPath, ConfigurationDataPath, AdditionalPath, OutputArchivePath, StorageEndpointSuffix, ContainerName, ParameterSetName, Force.IsPresent, SkipDependencyDetection.IsPresent, _storageCredentials); } finally { DeleteTemporaryFiles(); } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Discord.WebSocket { public partial class BaseSocketClient { //Channels /// <summary> Fired when a channel is created. </summary> /// <remarks> /// <para> /// This event is fired when a generic channel has been created. The event handler must return a /// <see cref="Task"/> and accept a <see cref="SocketChannel"/> as its parameter. /// </para> /// <para> /// The newly created channel is passed into the event handler parameter. The given channel type may /// include, but not limited to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category); /// see the derived classes of <see cref="SocketChannel"/> for more details. /// </para> /// </remarks> /// <example> /// <code language="cs" region="ChannelCreated" /// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/> /// </example> public event Func<SocketChannel, Task> ChannelCreated { add { _channelCreatedEvent.Add(value); } remove { _channelCreatedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketChannel, Task>> _channelCreatedEvent = new AsyncEvent<Func<SocketChannel, Task>>(); /// <summary> Fired when a channel is destroyed. </summary> /// <remarks> /// <para> /// This event is fired when a generic channel has been destroyed. The event handler must return a /// <see cref="Task"/> and accept a <see cref="SocketChannel"/> as its parameter. /// </para> /// <para> /// The destroyed channel is passed into the event handler parameter. The given channel type may /// include, but not limited to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category); /// see the derived classes of <see cref="SocketChannel"/> for more details. /// </para> /// </remarks> /// <example> /// <code language="cs" region="ChannelDestroyed" /// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/> /// </example> public event Func<SocketChannel, Task> ChannelDestroyed { add { _channelDestroyedEvent.Add(value); } remove { _channelDestroyedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketChannel, Task>> _channelDestroyedEvent = new AsyncEvent<Func<SocketChannel, Task>>(); /// <summary> Fired when a channel is updated. </summary> /// <remarks> /// <para> /// This event is fired when a generic channel has been destroyed. The event handler must return a /// <see cref="Task"/> and accept 2 <see cref="SocketChannel"/> as its parameters. /// </para> /// <para> /// The original (prior to update) channel is passed into the first <see cref="SocketChannel"/>, while /// the updated channel is passed into the second. The given channel type may include, but not limited /// to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category); see the derived classes of /// <see cref="SocketChannel"/> for more details. /// </para> /// </remarks> /// <example> /// <code language="cs" region="ChannelUpdated" /// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/> /// </example> public event Func<SocketChannel, SocketChannel, Task> ChannelUpdated { add { _channelUpdatedEvent.Add(value); } remove { _channelUpdatedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketChannel, SocketChannel, Task>> _channelUpdatedEvent = new AsyncEvent<Func<SocketChannel, SocketChannel, Task>>(); //Messages /// <summary> Fired when a message is received. </summary> /// <remarks> /// <para> /// This event is fired when a message is received. The event handler must return a /// <see cref="Task"/> and accept a <see cref="SocketMessage"/> as its parameter. /// </para> /// <para> /// The message that is sent to the client is passed into the event handler parameter as /// <see cref="SocketMessage"/>. This message may be a system message (i.e. /// <see cref="SocketSystemMessage"/>) or a user message (i.e. <see cref="SocketUserMessage"/>. See the /// derived classes of <see cref="SocketMessage"/> for more details. /// </para> /// </remarks> /// <example> /// <para>The example below checks if the newly received message contains the target user.</para> /// <code language="cs" region="MessageReceived" /// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/> /// </example> public event Func<SocketMessage, Task> MessageReceived { add { _messageReceivedEvent.Add(value); } remove { _messageReceivedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketMessage, Task>> _messageReceivedEvent = new AsyncEvent<Func<SocketMessage, Task>>(); /// <summary> Fired when a message is deleted. </summary> /// <remarks> /// <para> /// This event is fired when a message is deleted. The event handler must return a /// <see cref="Task"/> and accept a <see cref="Cacheable{TEntity,TId}"/> and /// <see cref="ISocketMessageChannel"/> as its parameters. /// </para> /// <para> /// <note type="important"> /// It is not possible to retrieve the message via /// <see cref="Cacheable{TEntity,TId}.DownloadAsync"/>; the message cannot be retrieved by Discord /// after the message has been deleted. /// </note> /// If caching is enabled via <see cref="DiscordSocketConfig"/>, the /// <see cref="Cacheable{TEntity,TId}"/> entity will contain the deleted message; otherwise, in event /// that the message cannot be retrieved, the snowflake ID of the message is preserved in the /// <see cref="ulong"/>. /// </para> /// <para> /// The source channel of the removed message will be passed into the /// <see cref="ISocketMessageChannel"/> parameter. /// </para> /// </remarks> /// <example> /// <code language="cs" region="MessageDeleted" /// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs" /> /// </example> public event Func<Cacheable<IMessage, ulong>, ISocketMessageChannel, Task> MessageDeleted { add { _messageDeletedEvent.Add(value); } remove { _messageDeletedEvent.Remove(value); } } internal readonly AsyncEvent<Func<Cacheable<IMessage, ulong>, ISocketMessageChannel, Task>> _messageDeletedEvent = new AsyncEvent<Func<Cacheable<IMessage, ulong>, ISocketMessageChannel, Task>>(); /// <summary> Fired when multiple messages are bulk deleted. </summary> /// <remarks> /// <note> /// The <see cref="MessageDeleted"/> event will not be fired for individual messages contained in this event. /// </note> /// <para> /// This event is fired when multiple messages are bulk deleted. The event handler must return a /// <see cref="Task"/> and accept an <see cref="IReadOnlyCollection{Cacheable}"/> and /// <see cref="ISocketMessageChannel"/> as its parameters. /// </para> /// <para> /// <note type="important"> /// It is not possible to retrieve the message via /// <see cref="Cacheable{TEntity,TId}.DownloadAsync"/>; the message cannot be retrieved by Discord /// after the message has been deleted. /// </note> /// If caching is enabled via <see cref="DiscordSocketConfig"/>, the /// <see cref="Cacheable{TEntity,TId}"/> entity will contain the deleted message; otherwise, in event /// that the message cannot be retrieved, the snowflake ID of the message is preserved in the /// <see cref="ulong"/>. /// </para> /// <para> /// The source channel of the removed message will be passed into the /// <see cref="ISocketMessageChannel"/> parameter. /// </para> /// </remarks> public event Func<IReadOnlyCollection<Cacheable<IMessage, ulong>>, ISocketMessageChannel, Task> MessagesBulkDeleted { add { _messagesBulkDeletedEvent.Add(value); } remove { _messagesBulkDeletedEvent.Remove(value); } } internal readonly AsyncEvent<Func<IReadOnlyCollection<Cacheable<IMessage, ulong>>, ISocketMessageChannel, Task>> _messagesBulkDeletedEvent = new AsyncEvent<Func<IReadOnlyCollection<Cacheable<IMessage, ulong>>, ISocketMessageChannel, Task>>(); /// <summary> Fired when a message is updated. </summary> /// <remarks> /// <para> /// This event is fired when a message is updated. The event handler must return a /// <see cref="Task"/> and accept a <see cref="Cacheable{TEntity,TId}"/>, <see cref="SocketMessage"/>, /// and <see cref="ISocketMessageChannel"/> as its parameters. /// </para> /// <para> /// If caching is enabled via <see cref="DiscordSocketConfig"/>, the /// <see cref="Cacheable{TEntity,TId}"/> entity will contain the original message; otherwise, in event /// that the message cannot be retrieved, the snowflake ID of the message is preserved in the /// <see cref="ulong"/>. /// </para> /// <para> /// The updated message will be passed into the <see cref="SocketMessage"/> parameter. /// </para> /// <para> /// The source channel of the updated message will be passed into the /// <see cref="ISocketMessageChannel"/> parameter. /// </para> /// </remarks> public event Func<Cacheable<IMessage, ulong>, SocketMessage, ISocketMessageChannel, Task> MessageUpdated { add { _messageUpdatedEvent.Add(value); } remove { _messageUpdatedEvent.Remove(value); } } internal readonly AsyncEvent<Func<Cacheable<IMessage, ulong>, SocketMessage, ISocketMessageChannel, Task>> _messageUpdatedEvent = new AsyncEvent<Func<Cacheable<IMessage, ulong>, SocketMessage, ISocketMessageChannel, Task>>(); /// <summary> Fired when a reaction is added to a message. </summary> /// <remarks> /// <para> /// This event is fired when a reaction is added to a user message. The event handler must return a /// <see cref="Task"/> and accept a <see cref="Cacheable{TEntity,TId}"/>, an /// <see cref="ISocketMessageChannel"/>, and a <see cref="SocketReaction"/> as its parameter. /// </para> /// <para> /// If caching is enabled via <see cref="DiscordSocketConfig"/>, the /// <see cref="Cacheable{TEntity,TId}"/> entity will contain the original message; otherwise, in event /// that the message cannot be retrieved, the snowflake ID of the message is preserved in the /// <see cref="ulong"/>. /// </para> /// <para> /// The source channel of the reaction addition will be passed into the /// <see cref="ISocketMessageChannel"/> parameter. /// </para> /// <para> /// The reaction that was added will be passed into the <see cref="SocketReaction"/> parameter. /// </para> /// <note> /// When fetching the reaction from this event, a user may not be provided under /// <see cref="SocketReaction.User"/>. Please see the documentation of the property for more /// information. /// </note> /// </remarks> /// <example> /// <code language="cs" region="ReactionAdded" /// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/> /// </example> public event Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task> ReactionAdded { add { _reactionAddedEvent.Add(value); } remove { _reactionAddedEvent.Remove(value); } } internal readonly AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task>> _reactionAddedEvent = new AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task>>(); /// <summary> Fired when a reaction is removed from a message. </summary> public event Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task> ReactionRemoved { add { _reactionRemovedEvent.Add(value); } remove { _reactionRemovedEvent.Remove(value); } } internal readonly AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task>> _reactionRemovedEvent = new AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task>>(); /// <summary> Fired when all reactions to a message are cleared. </summary> public event Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, Task> ReactionsCleared { add { _reactionsClearedEvent.Add(value); } remove { _reactionsClearedEvent.Remove(value); } } internal readonly AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, Task>> _reactionsClearedEvent = new AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, Task>>(); //Roles /// <summary> Fired when a role is created. </summary> public event Func<SocketRole, Task> RoleCreated { add { _roleCreatedEvent.Add(value); } remove { _roleCreatedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketRole, Task>> _roleCreatedEvent = new AsyncEvent<Func<SocketRole, Task>>(); /// <summary> Fired when a role is deleted. </summary> public event Func<SocketRole, Task> RoleDeleted { add { _roleDeletedEvent.Add(value); } remove { _roleDeletedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketRole, Task>> _roleDeletedEvent = new AsyncEvent<Func<SocketRole, Task>>(); /// <summary> Fired when a role is updated. </summary> public event Func<SocketRole, SocketRole, Task> RoleUpdated { add { _roleUpdatedEvent.Add(value); } remove { _roleUpdatedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketRole, SocketRole, Task>> _roleUpdatedEvent = new AsyncEvent<Func<SocketRole, SocketRole, Task>>(); //Guilds /// <summary> Fired when the connected account joins a guild. </summary> public event Func<SocketGuild, Task> JoinedGuild { add { _joinedGuildEvent.Add(value); } remove { _joinedGuildEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketGuild, Task>> _joinedGuildEvent = new AsyncEvent<Func<SocketGuild, Task>>(); /// <summary> Fired when the connected account leaves a guild. </summary> public event Func<SocketGuild, Task> LeftGuild { add { _leftGuildEvent.Add(value); } remove { _leftGuildEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketGuild, Task>> _leftGuildEvent = new AsyncEvent<Func<SocketGuild, Task>>(); /// <summary> Fired when a guild becomes available. </summary> public event Func<SocketGuild, Task> GuildAvailable { add { _guildAvailableEvent.Add(value); } remove { _guildAvailableEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketGuild, Task>> _guildAvailableEvent = new AsyncEvent<Func<SocketGuild, Task>>(); /// <summary> Fired when a guild becomes unavailable. </summary> public event Func<SocketGuild, Task> GuildUnavailable { add { _guildUnavailableEvent.Add(value); } remove { _guildUnavailableEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketGuild, Task>> _guildUnavailableEvent = new AsyncEvent<Func<SocketGuild, Task>>(); /// <summary> Fired when offline guild members are downloaded. </summary> public event Func<SocketGuild, Task> GuildMembersDownloaded { add { _guildMembersDownloadedEvent.Add(value); } remove { _guildMembersDownloadedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketGuild, Task>> _guildMembersDownloadedEvent = new AsyncEvent<Func<SocketGuild, Task>>(); /// <summary> Fired when a guild is updated. </summary> public event Func<SocketGuild, SocketGuild, Task> GuildUpdated { add { _guildUpdatedEvent.Add(value); } remove { _guildUpdatedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketGuild, SocketGuild, Task>> _guildUpdatedEvent = new AsyncEvent<Func<SocketGuild, SocketGuild, Task>>(); //Users /// <summary> Fired when a user joins a guild. </summary> public event Func<SocketGuildUser, Task> UserJoined { add { _userJoinedEvent.Add(value); } remove { _userJoinedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketGuildUser, Task>> _userJoinedEvent = new AsyncEvent<Func<SocketGuildUser, Task>>(); /// <summary> Fired when a user leaves a guild. </summary> public event Func<SocketGuildUser, Task> UserLeft { add { _userLeftEvent.Add(value); } remove { _userLeftEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketGuildUser, Task>> _userLeftEvent = new AsyncEvent<Func<SocketGuildUser, Task>>(); /// <summary> Fired when a user is banned from a guild. </summary> public event Func<SocketUser, SocketGuild, Task> UserBanned { add { _userBannedEvent.Add(value); } remove { _userBannedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketUser, SocketGuild, Task>> _userBannedEvent = new AsyncEvent<Func<SocketUser, SocketGuild, Task>>(); /// <summary> Fired when a user is unbanned from a guild. </summary> public event Func<SocketUser, SocketGuild, Task> UserUnbanned { add { _userUnbannedEvent.Add(value); } remove { _userUnbannedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketUser, SocketGuild, Task>> _userUnbannedEvent = new AsyncEvent<Func<SocketUser, SocketGuild, Task>>(); /// <summary> Fired when a user is updated. </summary> public event Func<SocketUser, SocketUser, Task> UserUpdated { add { _userUpdatedEvent.Add(value); } remove { _userUpdatedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketUser, SocketUser, Task>> _userUpdatedEvent = new AsyncEvent<Func<SocketUser, SocketUser, Task>>(); /// <summary> Fired when a guild member is updated, or a member presence is updated. </summary> public event Func<SocketGuildUser, SocketGuildUser, Task> GuildMemberUpdated { add { _guildMemberUpdatedEvent.Add(value); } remove { _guildMemberUpdatedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketGuildUser, SocketGuildUser, Task>> _guildMemberUpdatedEvent = new AsyncEvent<Func<SocketGuildUser, SocketGuildUser, Task>>(); /// <summary> Fired when a user joins, leaves, or moves voice channels. </summary> public event Func<SocketUser, SocketVoiceState, SocketVoiceState, Task> UserVoiceStateUpdated { add { _userVoiceStateUpdatedEvent.Add(value); } remove { _userVoiceStateUpdatedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketUser, SocketVoiceState, SocketVoiceState, Task>> _userVoiceStateUpdatedEvent = new AsyncEvent<Func<SocketUser, SocketVoiceState, SocketVoiceState, Task>>(); /// <summary> Fired when the bot connects to a Discord voice server. </summary> public event Func<SocketVoiceServer, Task> VoiceServerUpdated { add { _voiceServerUpdatedEvent.Add(value); } remove { _voiceServerUpdatedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketVoiceServer, Task>> _voiceServerUpdatedEvent = new AsyncEvent<Func<SocketVoiceServer, Task>>(); /// <summary> Fired when the connected account is updated. </summary> public event Func<SocketSelfUser, SocketSelfUser, Task> CurrentUserUpdated { add { _selfUpdatedEvent.Add(value); } remove { _selfUpdatedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketSelfUser, SocketSelfUser, Task>> _selfUpdatedEvent = new AsyncEvent<Func<SocketSelfUser, SocketSelfUser, Task>>(); /// <summary> Fired when a user starts typing. </summary> public event Func<SocketUser, ISocketMessageChannel, Task> UserIsTyping { add { _userIsTypingEvent.Add(value); } remove { _userIsTypingEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketUser, ISocketMessageChannel, Task>> _userIsTypingEvent = new AsyncEvent<Func<SocketUser, ISocketMessageChannel, Task>>(); /// <summary> Fired when a user joins a group channel. </summary> public event Func<SocketGroupUser, Task> RecipientAdded { add { _recipientAddedEvent.Add(value); } remove { _recipientAddedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketGroupUser, Task>> _recipientAddedEvent = new AsyncEvent<Func<SocketGroupUser, Task>>(); /// <summary> Fired when a user is removed from a group channel. </summary> public event Func<SocketGroupUser, Task> RecipientRemoved { add { _recipientRemovedEvent.Add(value); } remove { _recipientRemovedEvent.Remove(value); } } internal readonly AsyncEvent<Func<SocketGroupUser, Task>> _recipientRemovedEvent = new AsyncEvent<Func<SocketGroupUser, Task>>(); } }
#region License /* * HttpListenerContext.cs * * This code is derived from HttpListenerContext.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2016 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion using System; using System.Security.Principal; using WebSocketSharp.Net.WebSockets; namespace WebSocketSharp.Net { /// <summary> /// Provides the access to the HTTP request and response objects used by /// the <see cref="HttpListener"/>. /// </summary> /// <remarks> /// This class cannot be inherited. /// </remarks> public sealed class HttpListenerContext { #region Private Fields private HttpConnection _connection; private string _error; private int _errorStatus; private HttpListener _listener; private HttpListenerRequest _request; private HttpListenerResponse _response; private IPrincipal _user; private HttpListenerWebSocketContext _websocketContext; #endregion #region Internal Constructors internal HttpListenerContext (HttpConnection connection) { _connection = connection; _errorStatus = 400; _request = new HttpListenerRequest (this); _response = new HttpListenerResponse (this); } #endregion #region Internal Properties internal HttpConnection Connection { get { return _connection; } } internal string ErrorMessage { get { return _error; } set { _error = value; } } internal int ErrorStatus { get { return _errorStatus; } set { _errorStatus = value; } } internal bool HasError { get { return _error != null; } } internal HttpListener Listener { get { return _listener; } set { _listener = value; } } #endregion #region Public Properties /// <summary> /// Gets the HTTP request object that represents a client request. /// </summary> /// <value> /// A <see cref="HttpListenerRequest"/> that represents the client request. /// </value> public HttpListenerRequest Request { get { return _request; } } /// <summary> /// Gets the HTTP response object used to send a response to the client. /// </summary> /// <value> /// A <see cref="HttpListenerResponse"/> that represents a response to the client request. /// </value> public HttpListenerResponse Response { get { return _response; } } /// <summary> /// Gets the client information (identity, authentication, and security roles). /// </summary> /// <value> /// A <see cref="IPrincipal"/> instance that represents the client information. /// </value> public IPrincipal User { get { return _user; } } #endregion #region Internal Methods internal bool Authenticate () { var schm = _listener.SelectAuthenticationScheme (_request); if (schm == AuthenticationSchemes.Anonymous) return true; if (schm == AuthenticationSchemes.None) { _response.Close (HttpStatusCode.Forbidden); return false; } var realm = _listener.GetRealm (); var user = HttpUtility.CreateUser ( _request.Headers["Authorization"], schm, realm, _request.HttpMethod, _listener.GetUserCredentialsFinder () ); if (user == null || !user.Identity.IsAuthenticated) { _response.CloseWithAuthChallenge (new AuthenticationChallenge (schm, realm).ToString ()); return false; } _user = user; return true; } internal bool Register () { return _listener.RegisterContext (this); } internal void Unregister () { _listener.UnregisterContext (this); } #endregion #region Public Methods /// <summary> /// Accepts a WebSocket handshake request. /// </summary> /// <returns> /// A <see cref="HttpListenerWebSocketContext"/> that represents /// the WebSocket handshake request. /// </returns> /// <param name="protocol"> /// A <see cref="string"/> that represents the subprotocol supported on /// this WebSocket connection. /// </param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="protocol"/> is empty. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="protocol"/> contains an invalid character. /// </para> /// </exception> /// <exception cref="InvalidOperationException"> /// This method has already been called. /// </exception> public HttpListenerWebSocketContext AcceptWebSocket (string protocol) { if (_websocketContext != null) throw new InvalidOperationException ("The accepting is already in progress."); if (protocol != null) { if (protocol.Length == 0) throw new ArgumentException ("An empty string.", "protocol"); if (!protocol.IsToken ()) throw new ArgumentException ("Contains an invalid character.", "protocol"); } _websocketContext = new HttpListenerWebSocketContext (this, protocol); return _websocketContext; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web.Script.Serialization; using DbAppSettings.Model.DataTransfer; using DbAppSettings.Model.Domain; using NUnit.Framework; namespace DbAppSettings.Test.Model.Domain { [TestFixture] public class DbAppSettingTypeTest { class boolSetting : DbAppSetting<boolSetting, bool> { public override bool InitialValue => true; } [Test] public void DbAppSetting_bool() { boolSetting setting = new boolSetting(); Assert.IsTrue(setting.InitialValue == true); Assert.IsTrue(setting.InternalValue == true); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = false.ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == true); Assert.IsTrue(setting.InternalValue == false); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class byteSetting : DbAppSetting<byteSetting, byte> { public override byte InitialValue => Encoding.ASCII.GetBytes("test")[0]; } [Test] public void DbAppSetting_byte() { byteSetting setting = new byteSetting(); Assert.IsTrue(setting.InitialValue == Encoding.ASCII.GetBytes("test")[0]); Assert.IsTrue(setting.InternalValue == Encoding.ASCII.GetBytes("test")[0]); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = Encoding.ASCII.GetBytes("test")[1].ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == Encoding.ASCII.GetBytes("test")[0]); Assert.IsTrue(setting.InternalValue == Encoding.ASCII.GetBytes("test")[1]); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class charSetting : DbAppSetting<charSetting, char> { public override char InitialValue => 'a'; } [Test] public void DbAppSetting_char() { charSetting setting = new charSetting(); Assert.IsTrue(setting.InitialValue == 'a'); Assert.IsTrue(setting.InternalValue == 'a'); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = 'b'.ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == 'a'); Assert.IsTrue(setting.InternalValue == 'b'); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class decimalSetting : DbAppSetting<decimalSetting, decimal> { public override decimal InitialValue => 1.25M; } [Test] public void DbAppSetting_decimal() { decimalSetting setting = new decimalSetting(); Assert.IsTrue(setting.InitialValue == 1.25M); Assert.IsTrue(setting.InternalValue == 1.25M); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = 5.10M.ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == 1.25M); Assert.IsTrue(setting.InternalValue == 5.10M); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class doubleSetting : DbAppSetting<doubleSetting, double> { public override double InitialValue => 1.25; } [Test] public void DbAppSetting_double() { doubleSetting setting = new doubleSetting(); Assert.IsTrue(setting.InitialValue == 1.25); Assert.IsTrue(setting.InternalValue == 1.25); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = 5.10.ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == 1.25); Assert.IsTrue(setting.InternalValue == 5.10); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class floatSetting : DbAppSetting<floatSetting, float> { public override float InitialValue => 1.25F; } [Test] public void DbAppSetting_float() { floatSetting setting = new floatSetting(); Assert.IsTrue(setting.InitialValue == 1.25F); Assert.IsTrue(setting.InternalValue == 1.25F); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = 5.10F.ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == 1.25F); Assert.IsTrue(setting.InternalValue == 5.10F); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class intSetting : DbAppSetting<intSetting, int> { public override int InitialValue => 1; } [Test] public void DbAppSetting_int() { intSetting setting = new intSetting(); Assert.IsTrue(setting.InitialValue == 1); Assert.IsTrue(setting.InternalValue == 1); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = 5.ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == 1); Assert.IsTrue(setting.InternalValue == 5); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class longSetting : DbAppSetting<longSetting, long> { public override long InitialValue => 2147483648; } [Test] public void DbAppSetting_long() { longSetting setting = new longSetting(); Assert.IsTrue(setting.InitialValue == 2147483648); Assert.IsTrue(setting.InternalValue == 2147483648); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = 2147483649.ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == 2147483648); Assert.IsTrue(setting.InternalValue == 2147483649); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class sbyteSetting : DbAppSetting<sbyteSetting, sbyte> { public override sbyte InitialValue => -127; } [Test] public void DbAppSetting_sbyte() { sbyteSetting setting = new sbyteSetting(); Assert.IsTrue(setting.InitialValue == -127); Assert.IsTrue(setting.InternalValue == -127); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = 127.ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == -127); Assert.IsTrue(setting.InternalValue == 127); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class shortSetting : DbAppSetting<shortSetting, short> { public override short InitialValue => 1; } [Test] public void DbAppSetting_short() { shortSetting setting = new shortSetting(); Assert.IsTrue(setting.InitialValue == 1); Assert.IsTrue(setting.InternalValue == 1); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = 2.ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == 1); Assert.IsTrue(setting.InternalValue == 2); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class stringSetting : DbAppSetting<stringSetting, string> { public override string InitialValue => "test"; } [Test] public void DbAppSetting_string() { stringSetting setting = new stringSetting(); Assert.IsTrue(setting.InitialValue == "test"); Assert.IsTrue(setting.InternalValue == "test"); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = "new value".ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == "test"); Assert.IsTrue(setting.InternalValue == "new value"); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class StringCollectionSetting : DbAppSetting<StringCollectionSetting, StringCollection> { public override StringCollection InitialValue => new StringCollection { "One", "Two", "Three" }; } [Test] public void DbAppSetting_StringCollection() { List<string> initialStringList = new List<string> { "One", "Two", "Three" }; StringCollectionSetting setting = new StringCollectionSetting(); List<string> initialValueList = setting.InitialValue.Cast<string>().ToList(); Assert.IsTrue(initialStringList.SequenceEqual(initialValueList)); List<string> internalValueList = setting.InternalValue.Cast<string>().ToList(); Assert.IsTrue(initialStringList.SequenceEqual(internalValueList)); StringCollection newCollection = new StringCollection { "t", "3", "2" }; List<string> newStringList = new List<string> { "t", "3", "2" }; string jsonNewCollection = InternalDbAppSettingBase.ConvertStringCollectionToJson(newCollection); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = jsonNewCollection, Type = setting.TypeString }; setting.From(settingDto); initialValueList = setting.InitialValue.Cast<string>().ToList(); Assert.IsTrue(initialStringList.SequenceEqual(initialValueList)); internalValueList = setting.InternalValue.Cast<string>().ToList(); Assert.IsTrue(newStringList.SequenceEqual(internalValueList)); } class DateTimeSetting : DbAppSetting<DateTimeSetting, DateTime> { public override DateTime InitialValue => DateTime.Today; } [Test] public void DbAppSetting_DateTime() { DateTimeSetting setting = new DateTimeSetting(); Assert.IsTrue(setting.InitialValue == DateTime.Today); Assert.IsTrue(setting.InternalValue == DateTime.Today); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = DateTime.Today.AddDays(1).ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == DateTime.Today); Assert.IsTrue(setting.InternalValue == DateTime.Today.AddDays(1)); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class GuidSetting : DbAppSetting<GuidSetting, Guid> { public override Guid InitialValue => new Guid("9245fe4a-d402-451c-b9ed-9c1a04247482"); } [Test] public void DbAppSetting_Guid() { GuidSetting setting = new GuidSetting(); Assert.IsTrue(setting.InitialValue == new Guid("9245fe4a-d402-451c-b9ed-9c1a04247482")); Assert.IsTrue(setting.InternalValue == new Guid("9245fe4a-d402-451c-b9ed-9c1a04247482")); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = new Guid("1245fe4a-d402-451c-b9ed-9c1a04247482").ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == new Guid("9245fe4a-d402-451c-b9ed-9c1a04247482")); Assert.IsTrue(setting.InternalValue == new Guid("1245fe4a-d402-451c-b9ed-9c1a04247482")); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class TimeSpanSetting : DbAppSetting<TimeSpanSetting, TimeSpan> { public override TimeSpan InitialValue => new TimeSpan(1, 1, 1, 1); } [Test] public void DbAppSetting_TimeSpan() { TimeSpanSetting setting = new TimeSpanSetting(); Assert.IsTrue(setting.InitialValue == new TimeSpan(1, 1, 1, 1)); Assert.IsTrue(setting.InternalValue == new TimeSpan(1, 1, 1, 1)); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = new TimeSpan(2, 1, 1, 1).ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == new TimeSpan(1, 1, 1, 1)); Assert.IsTrue(setting.InternalValue == new TimeSpan(2, 1, 1, 1)); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class uintSetting : DbAppSetting<uintSetting, uint> { public override uint InitialValue => 4294967295; } [Test] public void DbAppSetting_uint() { uintSetting setting = new uintSetting(); Assert.IsTrue(setting.InitialValue == 4294967295); Assert.IsTrue(setting.InternalValue == 4294967295); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = 4294967294.ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == 4294967295); Assert.IsTrue(setting.InternalValue == 4294967294); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class ulongSetting : DbAppSetting<ulongSetting, ulong> { public override ulong InitialValue => 18446744073709551615; } [Test] public void DbAppSetting_ulong() { ulongSetting setting = new ulongSetting(); Assert.IsTrue(setting.InitialValue == 18446744073709551615); Assert.IsTrue(setting.InternalValue == 18446744073709551615); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = 18446744073709551614.ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == 18446744073709551615); Assert.IsTrue(setting.InternalValue == 18446744073709551614); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class ushortSetting : DbAppSetting<ushortSetting, ushort> { public override ushort InitialValue => 65535; } [Test] public void DbAppSetting_ushort() { ushortSetting setting = new ushortSetting(); Assert.IsTrue(setting.InitialValue == 65535); Assert.IsTrue(setting.InternalValue == 65535); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = 65534.ToString(), Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue == 65535); Assert.IsTrue(setting.InternalValue == 65534); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } class MyTestClass { public int SomeProperty { get; set; } = 1; public string SomeOtherProperty { get; set; } = "Test"; } class MyTestClassSetting : DbAppSetting<MyTestClassSetting, MyTestClass> { public override MyTestClass InitialValue => new MyTestClass(); } [Test] public void DbAppSetting_customObect() { MyTestClassSetting setting = new MyTestClassSetting(); Assert.IsTrue(setting.InitialValue.SomeProperty == 1); Assert.IsTrue(setting.InitialValue.SomeOtherProperty == "Test"); Assert.IsTrue(setting.InternalValue.SomeProperty == 1); Assert.IsTrue(setting.InternalValue.SomeOtherProperty == "Test"); MyTestClass testClass = new MyTestClass(); testClass.SomeProperty = 2; testClass.SomeOtherProperty = "Test2"; string jsonTestClass = new JavaScriptSerializer().Serialize(testClass); DbAppSettingDto settingDto = new DbAppSettingDto() { Key = setting.FullSettingName, Value = jsonTestClass, Type = setting.TypeString }; setting.From(settingDto); Assert.IsTrue(setting.InitialValue.SomeProperty == 1); Assert.IsTrue(setting.InitialValue.SomeOtherProperty == "Test"); Assert.IsTrue(setting.InternalValue.SomeProperty == 2); Assert.IsTrue(setting.InternalValue.SomeOtherProperty == "Test2"); DbAppSettingDto toDto = setting.ToDto(); Assert.IsTrue(toDto.ApplicationKey == settingDto.ApplicationKey); Assert.IsTrue(toDto.Key == settingDto.Key); Assert.IsTrue(toDto.Type == settingDto.Type); Assert.IsTrue(toDto.Value.Equals(settingDto.Value, StringComparison.InvariantCultureIgnoreCase)); } } }
// 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 Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Linq; using System.Runtime.InteropServices; using Xunit; using Roslyn.Test.PdbUtilities; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MissingAssemblyTests : ExpressionCompilerTestBase { [Fact] public void ErrorsWithAssemblyIdentityArguments() { var identity = new AssemblyIdentity(GetUniqueName()); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity)); } [Fact] public void ErrorsWithAssemblySymbolArguments() { var assembly = CreateCompilation("").Assembly; var identity = assembly.Identity; Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd, assembly)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, assembly)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_SingleTypeNameNotFoundFwd, assembly)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NameNotInContextPossibleMissingReference, assembly)); } [Fact] public void ErrorsRequiringSystemCore() { var identity = EvaluationContextBase.SystemCoreIdentity; Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NoSuchMemberOrExtension)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DynamicAttributeMissing)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DynamicRequiredTypesMissing)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_QueryNoProviderStandard)); Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_ExtensionAttrNotFound)); } [Fact] public void MultipleAssemblyArguments() { var identity1 = new AssemblyIdentity(GetUniqueName()); var identity2 = new AssemblyIdentity(GetUniqueName()); Assert.Equal(identity1, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity1, identity2)); Assert.Equal(identity2, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity2, identity1)); } [Fact] public void NoAssemblyArguments() { Assert.Null(GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef)); Assert.Null(GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, "Not an assembly")); } [Fact] public void ERR_NoTypeDef() { var libSource = @" public class Missing { } "; var source = @" public class C { public void M(Missing parameter) { } } "; var libRef = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib").EmitToImageReference(); var comp = CreateCompilationWithMscorlib(source, new[] { libRef }, TestOptions.DebugDll); var context = CreateMethodContextWithReferences(comp, "C.M", MscorlibRef); var expectedError = "error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'."; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Lib"); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "parameter", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [Fact] public void ERR_QueryNoProviderStandard() { var source = @" public class C { public void M(int[] array) { } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef }, TestOptions.DebugDll); var context = CreateMethodContextWithReferences(comp, "C.M", MscorlibRef); var expectedError = "(1,11): error CS1935: Could not find an implementation of the query pattern for source type 'int[]'. 'Select' not found. Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'?"; var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "from i in array select i", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [WorkItem(1151888, "DevDiv")] [Fact] public void ERR_NoSuchMemberOrExtension_CompilationReferencesSystemCore() { var source = @" using System.Linq; public class C { public void M(int[] array) { } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef }, TestOptions.DebugDll); var context = CreateMethodContextWithReferences(comp, "C.M", MscorlibRef); var expectedErrorTemplate = "error CS1061: 'int[]' does not contain a definition for '{0}' and no extension method '{0}' accepting a first argument of type 'int[]' could be found (are you missing a using directive or an assembly reference?)"; var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "array.Count()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(string.Format(expectedErrorTemplate, "Count"), actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( "array.NoSuchMethod()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(string.Format(expectedErrorTemplate, "NoSuchMethod"), actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } /// <remarks> /// The fact that the compilation does not reference System.Core has no effect since /// this test only covers our ability to identify an assembly to attempt to load, not /// our ability to actually load or consume it. /// </remarks> [WorkItem(1151888, "DevDiv")] [Fact] public void ERR_NoSuchMemberOrExtension_CompilationDoesNotReferenceSystemCore() { var source = @" using System.Linq; public class C { public void M(int[] array) { } } namespace System.Linq { public class Dummy { } } "; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); var context = CreateMethodContextWithReferences(comp, "C.M", MscorlibRef); var expectedErrorTemplate = "error CS1061: 'int[]' does not contain a definition for '{0}' and no extension method '{0}' accepting a first argument of type 'int[]' could be found (are you missing a using directive or an assembly reference?)"; var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "array.Count()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(string.Format(expectedErrorTemplate, "Count"), actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( "array.NoSuchMethod()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(string.Format(expectedErrorTemplate, "NoSuchMethod"), actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [Fact] public void ForwardingErrors() { var il = @" .assembly extern mscorlib { } .assembly extern pe2 { } .assembly pe1 { } .class extern forwarder Forwarded { .assembly extern pe2 } .class extern forwarder NS.Forwarded { .assembly extern pe2 } .class public auto ansi beforefieldinit Dummy extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var csharp = @" class C { static void M(Dummy d) { } } "; var ilRef = CompileIL(il, appendDefaultHeader: false); var comp = CreateCompilationWithMscorlib(csharp, new[] { ilRef }); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var expectedMissingAssemblyIdentity = new AssemblyIdentity("pe2"); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "new global::Forwarded()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal( "error CS1068: The type name 'Forwarded' could not be found in the global namespace. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Consider adding a reference to that assembly.", actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( "new Forwarded()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal( "error CS1070: The type name 'Forwarded' could not be found. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Consider adding a reference to that assembly.", actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); context.CompileExpression( "new NS.Forwarded()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal( "error CS1069: The type name 'Forwarded' could not be found in the namespace 'NS'. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Consider adding a reference to that assembly.", actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [Fact] public unsafe void ShouldTryAgain_Success() { var comp = CreateCompilationWithMscorlib("public class C { }"); using (var pinned = new PinnedMetadata(GetMetadataBytes(comp))) { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { uSize = (uint)pinned.Size; return pinned.Pointer; }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentity = new AssemblyIdentity("A"); var missingAssemblyIdentities = ImmutableArray.Create(missingAssemblyIdentity); Assert.True(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); var newReference = references.Single(); Assert.Equal(pinned.Pointer, newReference.Pointer); Assert.Equal(pinned.Size, newReference.Size); } } [Fact] public unsafe void ShouldTryAgain_Mixed() { var comp1 = CreateCompilationWithMscorlib("public class C { }", assemblyName: GetUniqueName()); var comp2 = CreateCompilationWithMscorlib("public class D { }", assemblyName: GetUniqueName()); using (PinnedMetadata pinned1 = new PinnedMetadata(GetMetadataBytes(comp1)), pinned2 = new PinnedMetadata(GetMetadataBytes(comp2))) { var assemblyIdentity1 = comp1.Assembly.Identity; var assemblyIdentity2 = comp2.Assembly.Identity; Assert.NotEqual(assemblyIdentity1, assemblyIdentity2); DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { if (assemblyIdentity == assemblyIdentity1) { uSize = (uint)pinned1.Size; return pinned1.Pointer; } else if (assemblyIdentity == assemblyIdentity2) { uSize = (uint)pinned2.Size; return pinned2.Pointer; } else { Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.CORDBG_E_MISSING_METADATA)); throw ExceptionUtilities.Unreachable; } }; var references = ImmutableArray.Create(default(MetadataBlock)); var unknownAssemblyIdentity = new AssemblyIdentity(GetUniqueName()); var missingAssemblyIdentities = ImmutableArray.Create(assemblyIdentity1, unknownAssemblyIdentity, assemblyIdentity2); Assert.True(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); Assert.Equal(3, references.Length); Assert.Equal(default(MetadataBlock), references[0]); Assert.Equal(pinned1.Pointer, references[1].Pointer); Assert.Equal(pinned1.Size, references[1].Size); Assert.Equal(pinned2.Pointer, references[2].Pointer); Assert.Equal(pinned2.Size, references[2].Size); } } [Fact] public void ShouldTryAgain_CORDBG_E_MISSING_METADATA() { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.CORDBG_E_MISSING_METADATA)); throw ExceptionUtilities.Unreachable; }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A")); Assert.False(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); Assert.Empty(references); } [Fact] public void ShouldTryAgain_COR_E_BADIMAGEFORMAT() { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.COR_E_BADIMAGEFORMAT)); throw ExceptionUtilities.Unreachable; }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A")); Assert.False(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); Assert.Empty(references); } [Fact] public void ShouldTryAgain_OtherException() { DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) => { throw new Exception(); }; var references = ImmutableArray<MetadataBlock>.Empty; var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A")); Assert.Throws<Exception>(() => ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references)); } [WorkItem(1124725, "DevDiv")] [Fact] public void PseudoVariableType() { var source = @"class C { static void M() { } } "; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); var context = CreateMethodContextWithReferences(comp, "C.M", CSharpRef, ExpressionCompilerTestHelpers.IntrinsicAssemblyReference); const string expectedError = "error CS0012: The type 'Exception' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'."; var expectedMissingAssemblyIdentity = comp.Assembly.CorLibrary.Identity; ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "$stowedexception", DkmEvaluationFlags.TreatAsExpression, ImmutableArray.Create(ExceptionAlias("Microsoft.CSharp.RuntimeBinder.RuntimeBinderException, Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", stowed: true)), DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [WorkItem(1114866)] [ConditionalFact(typeof(OSVersionWin8))] public void NotYetLoadedWinMds() { var source = @"class C { static void M(Windows.Storage.StorageFolder f) { } }"; var comp = CreateCompilationWithMscorlib(source, WinRtRefs, TestOptions.DebugDll); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage"); Assert.True(runtimeAssemblies.Any()); var context = CreateMethodContextWithReferences(comp, "C.M", ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies)); const string expectedError = "error CS0234: The type or namespace name 'UI' does not exist in the namespace 'Windows' (are you missing an assembly reference?)"; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Windows.UI", contentType: System.Reflection.AssemblyContentType.WindowsRuntime); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "typeof(@Windows.UI.Colors)", DkmEvaluationFlags.None, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } /// <remarks> /// Windows.UI.Xaml is the only (win8) winmd with more than two parts. /// </remarks> [WorkItem(1114866)] [ConditionalFact(typeof(OSVersionWin8))] public void NotYetLoadedWinMds_MultipleParts() { var source = @"class C { static void M(Windows.UI.Colors c) { } }"; var comp = CreateCompilationWithMscorlib(source, WinRtRefs, TestOptions.DebugDll); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI"); Assert.True(runtimeAssemblies.Any()); var context = CreateMethodContextWithReferences(comp, "C.M", ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies)); const string expectedError = "error CS0234: The type or namespace name 'Xaml' does not exist in the namespace 'Windows.UI' (are you missing an assembly reference?)"; var expectedMissingAssemblyIdentity = new AssemblyIdentity("Windows.UI.Xaml", contentType: System.Reflection.AssemblyContentType.WindowsRuntime); ResultProperties resultProperties; string actualError; ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities; context.CompileExpression( "typeof(Windows.@UI.Xaml.Application)", DkmEvaluationFlags.None, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out actualError, out actualMissingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal(expectedError, actualError); Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single()); } [WorkItem(1154988)] [Fact] public void CompileWithRetrySameErrorReported() { var source = @" class C { void M() { } }"; var comp = CreateCompilationWithMscorlib(source); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var missingModule = runtime.Modules.First(); var missingIdentity = missingModule.MetadataReader.ReadAssemblyIdentityOrThrow(); var numRetries = 0; string errorMessage; ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(), context, (_, diagnostics) => { numRetries++; Assert.InRange(numRetries, 0, 2); // We don't want to loop forever... diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_NoTypeDef, "MissingType", missingIdentity), Location.None)); return null; }, (AssemblyIdentity assemblyIdentity, out uint uSize) => { uSize = (uint)missingModule.MetadataLength; return missingModule.MetadataAddress; }, out errorMessage); Assert.Equal(2, numRetries); // Ensure that we actually retried and that we bailed out on the second retry if the same identity was seen in the diagnostics. Assert.Equal($"error CS0012: The type 'MissingType' is defined in an assembly that is not referenced. You must add a reference to assembly '{missingIdentity}'.", errorMessage); } [WorkItem(1151888)] [Fact] public void SucceedOnRetry() { var source = @" class C { void M() { } }"; var comp = CreateCompilationWithMscorlib(source); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "C.M"); var missingModule = runtime.Modules.First(); var missingIdentity = missingModule.MetadataReader.ReadAssemblyIdentityOrThrow(); var shouldSucceed = false; string errorMessage; var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(), context, (_, diagnostics) => { if (shouldSucceed) { return TestCompileResult.Instance; } else { shouldSucceed = true; diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_NoTypeDef, "MissingType", missingIdentity), Location.None)); return null; } }, (AssemblyIdentity assemblyIdentity, out uint uSize) => { uSize = (uint)missingModule.MetadataLength; return missingModule.MetadataAddress; }, out errorMessage); Assert.Same(TestCompileResult.Instance, compileResult); Assert.Null(errorMessage); } [WorkItem(2547)] [Fact] public void TryDifferentLinqLibraryOnRetry() { var source = @" using System.Linq; class C { void M(string[] args) { } } class UseLinq { bool b = Enumerable.Any<int>(null); }"; var compilation = CreateCompilationWithMscorlibAndSystemCore(source); byte[] exeBytes, pdbBytes; ImmutableArray<MetadataReference> references; compilation.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var systemCore = SystemCoreRef.ToModuleInstance(fullImage: null, symReader: null); var referencesWithoutSystemCore = references.Where(r => r != SystemCoreRef).ToImmutableArray(); var runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), referencesWithoutSystemCore.AddIntrinsicAssembly(), exeBytes, symReader: null); var context = CreateMethodContext(runtime, "C.M"); var fakeSystemLinq = CreateCompilationWithMscorlib45("", assemblyName: "System.Linq").EmitToImageReference().ToModuleInstance(fullImage: null, symReader: null); string errorMessage; CompilationTestData testData; int retryCount = 0; var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(), "args.Where(a => a.Length > 0)", (_1, _2) => context, // ignore new blocks and just keep using the same failed context... (AssemblyIdentity assemblyIdentity, out uint uSize) => { retryCount++; MetadataBlock block; switch (retryCount) { case 1: Assert.Equal(EvaluationContextBase.SystemLinqIdentity, assemblyIdentity); block = fakeSystemLinq.MetadataBlock; break; case 2: Assert.Equal(EvaluationContextBase.SystemCoreIdentity, assemblyIdentity); block = systemCore.MetadataBlock; break; default: throw ExceptionUtilities.Unreachable; } uSize = (uint)block.Size; return block.Pointer; }, errorMessage: out errorMessage, testData: out testData); Assert.Equal(2, retryCount); } private sealed class TestCompileResult : CompileResult { public static readonly CompileResult Instance = new TestCompileResult(); private TestCompileResult() : base(null, null, null, null) { } public override CustomTypeInfo GetCustomTypeInfo() { throw new NotImplementedException(); } } private EvaluationContext CreateMethodContextWithReferences(Compilation comp, string methodName, params MetadataReference[] references) { return CreateMethodContextWithReferences(comp, methodName, ImmutableArray.CreateRange(references)); } private EvaluationContext CreateMethodContextWithReferences(Compilation comp, string methodName, ImmutableArray<MetadataReference> references) { byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> unusedReferences; var result = comp.EmitAndGetReferences(out exeBytes, out pdbBytes, out unusedReferences); Assert.True(result); var runtime = CreateRuntimeInstance(GetUniqueName(), references, exeBytes, new SymReader(pdbBytes)); return CreateMethodContext(runtime, methodName); } private static AssemblyIdentity GetMissingAssemblyIdentity(ErrorCode code, params object[] arguments) { var missingAssemblyIdentities = EvaluationContext.GetMissingAssemblyIdentitiesHelper(code, arguments, EvaluationContextBase.SystemCoreIdentity); return missingAssemblyIdentities.IsDefault ? null : missingAssemblyIdentities.Single(); } private static ImmutableArray<byte> GetMetadataBytes(Compilation comp) { var imageReference = (MetadataImageReference)comp.EmitToImageReference(); var assemblyMetadata = (AssemblyMetadata)imageReference.GetMetadata(); var moduleMetadata = assemblyMetadata.GetModules()[0]; return moduleMetadata.Module.PEReaderOpt.GetMetadata().GetContent(); } } }
// 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.Security; using System; using System.IO; [SecuritySafeCritical] public class TestFileStream : FileStream { public TestFileStream(string path, FileMode mode) : base(path, mode) { } public void DisposeWrapper(bool disposing) { Dispose(disposing); } public override bool CanRead { [SecuritySafeCritical] get { throw new Exception("The method or operation is not implemented."); } } public override bool CanSeek { [SecuritySafeCritical] get { return base.CanSeek; } } public override bool CanWrite { [SecuritySafeCritical] get { throw new Exception("The method or operation is not implemented."); } } [SecuritySafeCritical] public override void Flush() { throw new Exception("The method or operation is not implemented."); } public override long Length { [SecuritySafeCritical] get { throw new Exception("The method or operation is not implemented."); } } public override long Position { [SecuritySafeCritical] get { throw new Exception("The method or operation is not implemented."); } [SecuritySafeCritical] set { throw new Exception("The method or operation is not implemented."); } } [SecuritySafeCritical] public override int Read(byte[] buffer, int offset, int count) { throw new Exception("The method or operation is not implemented."); } [SecuritySafeCritical] public override long Seek(long offset, SeekOrigin origin) { throw new Exception("The method or operation is not implemented."); } [SecuritySafeCritical] public override void SetLength(long value) { throw new Exception("The method or operation is not implemented."); } [SecuritySafeCritical] public override void Write(byte[] buffer, int offset, int count) { throw new Exception("The method or operation is not implemented."); } } [SecuritySafeCritical] public class FileStreamDispose { #region Private Fileds const string c_DEFAULT_FILE_PATH = "TestFile"; #endregion #region Public Methods public bool RunTesfs() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; // // TODO: Add your negative test cases here // // TestLibrary.TestFramework.LogInformation("[Negative]"); // retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call Dispose with disposing set to true"); try { TestFileStream tfs = new TestFileStream(c_DEFAULT_FILE_PATH,FileMode.Append); tfs.DisposeWrapper(true); } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Call Dispose twice with disposing set to true"); try { TestFileStream tfs = new TestFileStream(c_DEFAULT_FILE_PATH, FileMode.Append); tfs.DisposeWrapper(true); tfs.DisposeWrapper(true); } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Call Dispose with disposing set to false"); try { TestFileStream tfs = new TestFileStream(c_DEFAULT_FILE_PATH, FileMode.Append); tfs.DisposeWrapper(false); } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Call Dispose twice with disposing set to false"); try { TestFileStream tfs = new TestFileStream(c_DEFAULT_FILE_PATH, FileMode.Append); tfs.DisposeWrapper(false); tfs.DisposeWrapper(false); } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Call Dispose twice with disposing set to false once and another time set to true"); try { TestFileStream tfs = new TestFileStream(c_DEFAULT_FILE_PATH, FileMode.Append); tfs.DisposeWrapper(false); tfs.DisposeWrapper(true); } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Call Dispose twice with disposing set to true once and another time set to false"); try { TestFileStream tfs = new TestFileStream(c_DEFAULT_FILE_PATH, FileMode.Append); tfs.DisposeWrapper(true); tfs.DisposeWrapper(false); } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { FileStreamDispose test = new FileStreamDispose(); TestLibrary.TestFramework.BeginTestCase("FileStreamDispose"); if (test.RunTesfs()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; namespace log4net.Core { /// <summary> /// A strongly-typed collection of <see cref="Level"/> objects. /// </summary> /// <author>Nicko Cadell</author> public class LevelCollection : ICollection, IList, IEnumerable #if !NETSTANDARD1_3 , ICloneable #endif { #region Interfaces /// <summary> /// Supports type-safe iteration over a <see cref="LevelCollection"/>. /// </summary> public interface ILevelCollectionEnumerator { /// <summary> /// Gets the current element in the collection. /// </summary> Level Current { get; } /// <summary> /// Advances the enumerator to the next element in the collection. /// </summary> /// <returns> /// <c>true</c> if the enumerator was successfully advanced to the next element; /// <c>false</c> if the enumerator has passed the end of the collection. /// </returns> /// <exception cref="InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> bool MoveNext(); /// <summary> /// Sets the enumerator to its initial position, before the first element in the collection. /// </summary> void Reset(); } #endregion private const int DEFAULT_CAPACITY = 16; #region Implementation (data) private Level[] m_array; private int m_count = 0; private int m_version = 0; #endregion #region Static Wrappers /// <summary> /// Creates a read-only wrapper for a <c>LevelCollection</c> instance. /// </summary> /// <param name="list">list to create a readonly wrapper arround</param> /// <returns> /// A <c>LevelCollection</c> wrapper that is read-only. /// </returns> public static LevelCollection ReadOnly(LevelCollection list) { if(list==null) throw new ArgumentNullException("list"); return new ReadOnlyLevelCollection(list); } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that is empty and has the default initial capacity. /// </summary> public LevelCollection() { m_array = new Level[DEFAULT_CAPACITY]; } /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that has the specified initial capacity. /// </summary> /// <param name="capacity"> /// The number of elements that the new <c>LevelCollection</c> is initially capable of storing. /// </param> public LevelCollection(int capacity) { m_array = new Level[capacity]; } /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that contains elements copied from the specified <c>LevelCollection</c>. /// </summary> /// <param name="c">The <c>LevelCollection</c> whose elements are copied to the new collection.</param> public LevelCollection(LevelCollection c) { m_array = new Level[c.Count]; AddRange(c); } /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that contains elements copied from the specified <see cref="Level"/> array. /// </summary> /// <param name="a">The <see cref="Level"/> array whose elements are copied to the new list.</param> public LevelCollection(Level[] a) { m_array = new Level[a.Length]; AddRange(a); } /// <summary> /// Initializes a new instance of the <c>LevelCollection</c> class /// that contains elements copied from the specified <see cref="Level"/> collection. /// </summary> /// <param name="col">The <see cref="Level"/> collection whose elements are copied to the new list.</param> public LevelCollection(ICollection col) { m_array = new Level[col.Count]; AddRange(col); } /// <summary> /// Type visible only to our subclasses /// Used to access protected constructor /// </summary> protected internal enum Tag { /// <summary> /// A value /// </summary> Default } /// <summary> /// Allow subclasses to avoid our default constructors /// </summary> /// <param name="tag"></param> protected internal LevelCollection(Tag tag) { m_array = null; } #endregion #region Operations (type-safe ICollection) /// <summary> /// Gets the number of elements actually contained in the <c>LevelCollection</c>. /// </summary> public virtual int Count { get { return m_count; } } /// <summary> /// Copies the entire <c>LevelCollection</c> to a one-dimensional /// <see cref="Level"/> array. /// </summary> /// <param name="array">The one-dimensional <see cref="Level"/> array to copy to.</param> public virtual void CopyTo(Level[] array) { this.CopyTo(array, 0); } /// <summary> /// Copies the entire <c>LevelCollection</c> to a one-dimensional /// <see cref="Level"/> array, starting at the specified index of the target array. /// </summary> /// <param name="array">The one-dimensional <see cref="Level"/> array to copy to.</param> /// <param name="start">The zero-based index in <paramref name="array"/> at which copying begins.</param> public virtual void CopyTo(Level[] array, int start) { if (m_count > array.GetUpperBound(0) + 1 - start) { throw new System.ArgumentException("Destination array was not long enough."); } Array.Copy(m_array, 0, array, start, m_count); } /// <summary> /// Gets a value indicating whether access to the collection is synchronized (thread-safe). /// </summary> /// <returns>false, because the backing type is an array, which is never thread-safe.</returns> public virtual bool IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the collection. /// </summary> public virtual object SyncRoot { get { return m_array; } } #endregion #region Operations (type-safe IList) /// <summary> /// Gets or sets the <see cref="Level"/> at the specified index. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> public virtual Level this[int index] { get { ValidateIndex(index); // throws return m_array[index]; } set { ValidateIndex(index); // throws ++m_version; m_array[index] = value; } } /// <summary> /// Adds a <see cref="Level"/> to the end of the <c>LevelCollection</c>. /// </summary> /// <param name="item">The <see cref="Level"/> to be added to the end of the <c>LevelCollection</c>.</param> /// <returns>The index at which the value has been added.</returns> public virtual int Add(Level item) { if (m_count == m_array.Length) { EnsureCapacity(m_count + 1); } m_array[m_count] = item; m_version++; return m_count++; } /// <summary> /// Removes all elements from the <c>LevelCollection</c>. /// </summary> public virtual void Clear() { ++m_version; m_array = new Level[DEFAULT_CAPACITY]; m_count = 0; } /// <summary> /// Creates a shallow copy of the <see cref="LevelCollection"/>. /// </summary> /// <returns>A new <see cref="LevelCollection"/> with a shallow copy of the collection data.</returns> public virtual object Clone() { LevelCollection newCol = new LevelCollection(m_count); Array.Copy(m_array, 0, newCol.m_array, 0, m_count); newCol.m_count = m_count; newCol.m_version = m_version; return newCol; } /// <summary> /// Determines whether a given <see cref="Level"/> is in the <c>LevelCollection</c>. /// </summary> /// <param name="item">The <see cref="Level"/> to check for.</param> /// <returns><c>true</c> if <paramref name="item"/> is found in the <c>LevelCollection</c>; otherwise, <c>false</c>.</returns> public virtual bool Contains(Level item) { for (int i=0; i != m_count; ++i) { if (m_array[i].Equals(item)) { return true; } } return false; } /// <summary> /// Returns the zero-based index of the first occurrence of a <see cref="Level"/> /// in the <c>LevelCollection</c>. /// </summary> /// <param name="item">The <see cref="Level"/> to locate in the <c>LevelCollection</c>.</param> /// <returns> /// The zero-based index of the first occurrence of <paramref name="item"/> /// in the entire <c>LevelCollection</c>, if found; otherwise, -1. /// </returns> public virtual int IndexOf(Level item) { for (int i=0; i != m_count; ++i) { if (m_array[i].Equals(item)) { return i; } } return -1; } /// <summary> /// Inserts an element into the <c>LevelCollection</c> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> /// <param name="item">The <see cref="Level"/> to insert.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> public virtual void Insert(int index, Level item) { ValidateIndex(index, true); // throws if (m_count == m_array.Length) { EnsureCapacity(m_count + 1); } if (index < m_count) { Array.Copy(m_array, index, m_array, index + 1, m_count - index); } m_array[index] = item; m_count++; m_version++; } /// <summary> /// Removes the first occurrence of a specific <see cref="Level"/> from the <c>LevelCollection</c>. /// </summary> /// <param name="item">The <see cref="Level"/> to remove from the <c>LevelCollection</c>.</param> /// <exception cref="ArgumentException"> /// The specified <see cref="Level"/> was not found in the <c>LevelCollection</c>. /// </exception> public virtual void Remove(Level item) { int i = IndexOf(item); if (i < 0) { throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); } ++m_version; RemoveAt(i); } /// <summary> /// Removes the element at the specified index of the <c>LevelCollection</c>. /// </summary> /// <param name="index">The zero-based index of the element to remove.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> public virtual void RemoveAt(int index) { ValidateIndex(index); // throws m_count--; if (index < m_count) { Array.Copy(m_array, index + 1, m_array, index, m_count - index); } // We can't set the deleted entry equal to null, because it might be a value type. // Instead, we'll create an empty single-element array of the right type and copy it // over the entry we want to erase. Level[] temp = new Level[1]; Array.Copy(temp, 0, m_array, m_count, 1); m_version++; } /// <summary> /// Gets a value indicating whether the collection has a fixed size. /// </summary> /// <value>true if the collection has a fixed size; otherwise, false. The default is false</value> public virtual bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the IList is read-only. /// </summary> /// <value>true if the collection is read-only; otherwise, false. The default is false</value> public virtual bool IsReadOnly { get { return false; } } #endregion #region Operations (type-safe IEnumerable) /// <summary> /// Returns an enumerator that can iterate through the <c>LevelCollection</c>. /// </summary> /// <returns>An <see cref="Enumerator"/> for the entire <c>LevelCollection</c>.</returns> public virtual ILevelCollectionEnumerator GetEnumerator() { return new Enumerator(this); } #endregion #region Public helpers (just to mimic some nice features of ArrayList) /// <summary> /// Gets or sets the number of elements the <c>LevelCollection</c> can contain. /// </summary> public virtual int Capacity { get { return m_array.Length; } set { if (value < m_count) { value = m_count; } if (value != m_array.Length) { if (value > 0) { Level[] temp = new Level[value]; Array.Copy(m_array, 0, temp, 0, m_count); m_array = temp; } else { m_array = new Level[DEFAULT_CAPACITY]; } } } } /// <summary> /// Adds the elements of another <c>LevelCollection</c> to the current <c>LevelCollection</c>. /// </summary> /// <param name="x">The <c>LevelCollection</c> whose elements should be added to the end of the current <c>LevelCollection</c>.</param> /// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns> public virtual int AddRange(LevelCollection x) { if (m_count + x.Count >= m_array.Length) { EnsureCapacity(m_count + x.Count); } Array.Copy(x.m_array, 0, m_array, m_count, x.Count); m_count += x.Count; m_version++; return m_count; } /// <summary> /// Adds the elements of a <see cref="Level"/> array to the current <c>LevelCollection</c>. /// </summary> /// <param name="x">The <see cref="Level"/> array whose elements should be added to the end of the <c>LevelCollection</c>.</param> /// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns> public virtual int AddRange(Level[] x) { if (m_count + x.Length >= m_array.Length) { EnsureCapacity(m_count + x.Length); } Array.Copy(x, 0, m_array, m_count, x.Length); m_count += x.Length; m_version++; return m_count; } /// <summary> /// Adds the elements of a <see cref="Level"/> collection to the current <c>LevelCollection</c>. /// </summary> /// <param name="col">The <see cref="Level"/> collection whose elements should be added to the end of the <c>LevelCollection</c>.</param> /// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns> public virtual int AddRange(ICollection col) { if (m_count + col.Count >= m_array.Length) { EnsureCapacity(m_count + col.Count); } foreach(object item in col) { Add((Level)item); } return m_count; } /// <summary> /// Sets the capacity to the actual number of elements. /// </summary> public virtual void TrimToSize() { this.Capacity = m_count; } #endregion #region Implementation (helpers) /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="i"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="i"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> private void ValidateIndex(int i) { ValidateIndex(i, false); } /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="i"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="i"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para> /// </exception> private void ValidateIndex(int i, bool allowEqualEnd) { int max = (allowEqualEnd) ? (m_count) : (m_count-1); if (i < 0 || i > max) { throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); } } private void EnsureCapacity(int min) { int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2); if (newCapacity < min) { newCapacity = min; } this.Capacity = newCapacity; } #endregion #region Implementation (ICollection) void ICollection.CopyTo(Array array, int start) { Array.Copy(m_array, 0, array, start, m_count); } #endregion #region Implementation (IList) object IList.this[int i] { get { return (object)this[i]; } set { this[i] = (Level)value; } } int IList.Add(object x) { return this.Add((Level)x); } bool IList.Contains(object x) { return this.Contains((Level)x); } int IList.IndexOf(object x) { return this.IndexOf((Level)x); } void IList.Insert(int pos, object x) { this.Insert(pos, (Level)x); } void IList.Remove(object x) { this.Remove((Level)x); } void IList.RemoveAt(int pos) { this.RemoveAt(pos); } #endregion #region Implementation (IEnumerable) IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)(this.GetEnumerator()); } #endregion #region Nested enumerator class /// <summary> /// Supports simple iteration over a <see cref="LevelCollection"/>. /// </summary> private sealed class Enumerator : IEnumerator, ILevelCollectionEnumerator { #region Implementation (data) private readonly LevelCollection m_collection; private int m_index; private int m_version; #endregion #region Construction /// <summary> /// Initializes a new instance of the <c>Enumerator</c> class. /// </summary> /// <param name="tc"></param> internal Enumerator(LevelCollection tc) { m_collection = tc; m_index = -1; m_version = tc.m_version; } #endregion #region Operations (type-safe IEnumerator) /// <summary> /// Gets the current element in the collection. /// </summary> public Level Current { get { return m_collection[m_index]; } } /// <summary> /// Advances the enumerator to the next element in the collection. /// </summary> /// <returns> /// <c>true</c> if the enumerator was successfully advanced to the next element; /// <c>false</c> if the enumerator has passed the end of the collection. /// </returns> /// <exception cref="InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> public bool MoveNext() { if (m_version != m_collection.m_version) { throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); } ++m_index; return (m_index < m_collection.Count); } /// <summary> /// Sets the enumerator to its initial position, before the first element in the collection. /// </summary> public void Reset() { m_index = -1; } #endregion #region Implementation (IEnumerator) object IEnumerator.Current { get { return this.Current; } } #endregion } #endregion #region Nested Read Only Wrapper class private sealed class ReadOnlyLevelCollection : LevelCollection { #region Implementation (data) private readonly LevelCollection m_collection; #endregion #region Construction internal ReadOnlyLevelCollection(LevelCollection list) : base(Tag.Default) { m_collection = list; } #endregion #region Type-safe ICollection public override void CopyTo(Level[] array) { m_collection.CopyTo(array); } public override void CopyTo(Level[] array, int start) { m_collection.CopyTo(array,start); } public override int Count { get { return m_collection.Count; } } public override bool IsSynchronized { get { return m_collection.IsSynchronized; } } public override object SyncRoot { get { return this.m_collection.SyncRoot; } } #endregion #region Type-safe IList public override Level this[int i] { get { return m_collection[i]; } set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } } public override int Add(Level x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override void Clear() { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override bool Contains(Level x) { return m_collection.Contains(x); } public override int IndexOf(Level x) { return m_collection.IndexOf(x); } public override void Insert(int pos, Level x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override void Remove(Level x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override void RemoveAt(int pos) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override bool IsFixedSize { get { return true; } } public override bool IsReadOnly { get { return true; } } #endregion #region Type-safe IEnumerable public override ILevelCollectionEnumerator GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region Public Helpers // (just to mimic some nice features of ArrayList) public override int Capacity { get { return m_collection.Capacity; } set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } } public override int AddRange(LevelCollection x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override int AddRange(Level[] x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } #endregion } #endregion } }
using CppSharp.AST; using CppSharp.Types; using System; using System.Collections.Generic; namespace CppSharp.Generators { public class TypePrinterResult { public string Type; public TypeMap TypeMap; public string NameSuffix; public static implicit operator TypePrinterResult(string type) { return new TypePrinterResult { Type = type }; } public override string ToString() => Type; } public class TypePrinter : ITypePrinter<TypePrinterResult>, IDeclVisitor<TypePrinterResult> { #region Dummy implementations public virtual string ToString(CppSharp.AST.Type type) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitArrayType(ArrayType array, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitAttributedType(AttributedType attributed, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitCILType(CILType type, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitClassDecl(Class @class) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitClassTemplateDecl(ClassTemplate template) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitClassTemplateSpecializationDecl( ClassTemplateSpecialization specialization) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitDecayedType(DecayedType decayed, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitDeclaration(Declaration decl) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitDeclaration(Declaration decl, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitDelegate(FunctionType function) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitDependentNameType( DependentNameType dependent, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitDependentTemplateSpecializationType( DependentTemplateSpecializationType template, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitEnumDecl(Enumeration @enum) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitEnumItemDecl(Enumeration.Item item) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitEvent(Event @event) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitFieldDecl(Field field) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitFriend(Friend friend) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitFunctionDecl(Function function) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitFunctionTemplateDecl( FunctionTemplate template) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitFunctionTemplateSpecializationDecl( FunctionTemplateSpecialization specialization) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitFunctionType(FunctionType function, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitInjectedClassNameType( InjectedClassNameType injected, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitMacroDefinition(MacroDefinition macro) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitMemberPointerType( MemberPointerType member, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitMethodDecl(Method method) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitNamespace(Namespace @namespace) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitNonTypeTemplateParameterDecl( NonTypeTemplateParameter nonTypeTemplateParameter) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitPackExpansionType( PackExpansionType packExpansionType, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitParameter(Parameter param, bool hasName = true) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitParameterDecl(Parameter parameter) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitParameters(IEnumerable<Parameter> @params, bool hasNames = true) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitPointerType(PointerType pointer, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitProperty(Property property) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitTagType(TagType tag, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitTemplateParameterDecl( TypeTemplateParameter templateParameter) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitTemplateParameterSubstitutionType( TemplateParameterSubstitutionType param, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitTemplateParameterType( TemplateParameterType param, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitTemplateSpecializationType( TemplateSpecializationType template, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitTemplateTemplateParameterDecl( TemplateTemplateParameter templateTemplateParameter) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitTypeAliasDecl(TypeAlias typeAlias) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitTypeAliasTemplateDecl( TypeAliasTemplate typeAliasTemplate) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitTypedefDecl(TypedefDecl typedef) { throw new NotImplementedException(); } public TypePrinterResult VisitTypedefNameDecl(TypedefNameDecl typedef) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitTypedefType(TypedefType typedef, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitUnaryTransformType( UnaryTransformType unaryTransformType, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitUnsupportedType(UnsupportedType type, TypeQualifiers quals) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitVariableDecl(Variable variable) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitVarTemplateDecl(VarTemplate template) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitVarTemplateSpecializationDecl( VarTemplateSpecialization template) { throw new NotImplementedException(); } public virtual TypePrinterResult VisitVectorType(VectorType vectorType, TypeQualifiers quals) { throw new NotImplementedException(); } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Classes: Object Security family of classes ** ** ===========================================================*/ using Microsoft.Win32; using System; using System.Collections; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime.ExceptionServices; #endif // FEATURE_CORRUPTING_EXCEPTIONS using System.Security.Principal; using System.Threading; using System.Diagnostics.Contracts; namespace System.Security.AccessControl { public enum AccessControlModification { Add = 0, Set = 1, Reset = 2, Remove = 3, RemoveAll = 4, RemoveSpecific = 5, } public abstract class ObjectSecurity { #region Private Members private readonly ReaderWriterLock _lock = new ReaderWriterLock(); internal CommonSecurityDescriptor _securityDescriptor; private bool _ownerModified = false; private bool _groupModified = false; private bool _saclModified = false; private bool _daclModified = false; // only these SACL control flags will be automatically carry forward // when update with new security descriptor. static private readonly ControlFlags SACL_CONTROL_FLAGS = ControlFlags.SystemAclPresent | ControlFlags.SystemAclAutoInherited | ControlFlags.SystemAclProtected; // only these DACL control flags will be automatically carry forward // when update with new security descriptor static private readonly ControlFlags DACL_CONTROL_FLAGS = ControlFlags.DiscretionaryAclPresent | ControlFlags.DiscretionaryAclAutoInherited | ControlFlags.DiscretionaryAclProtected; #endregion #region Constructors protected ObjectSecurity() { } protected ObjectSecurity( bool isContainer, bool isDS ) : this() { // we will create an empty DACL, denying anyone any access as the default. 5 is the capacity. DiscretionaryAcl dacl = new DiscretionaryAcl(isContainer, isDS, 5); _securityDescriptor = new CommonSecurityDescriptor( isContainer, isDS, ControlFlags.None, null, null, null, dacl ); } protected ObjectSecurity( CommonSecurityDescriptor securityDescriptor ) : this() { if ( securityDescriptor == null ) { throw new ArgumentNullException( "securityDescriptor" ); } Contract.EndContractBlock(); _securityDescriptor = securityDescriptor; } #endregion #region Private methods private void UpdateWithNewSecurityDescriptor( RawSecurityDescriptor newOne, AccessControlSections includeSections ) { Contract.Assert( newOne != null, "Must not supply a null parameter here" ); if (( includeSections & AccessControlSections.Owner ) != 0 ) { _ownerModified = true; _securityDescriptor.Owner = newOne.Owner; } if (( includeSections & AccessControlSections.Group ) != 0 ) { _groupModified = true; _securityDescriptor.Group = newOne.Group; } if (( includeSections & AccessControlSections.Audit ) != 0 ) { _saclModified = true; if ( newOne.SystemAcl != null ) { _securityDescriptor.SystemAcl = new SystemAcl( IsContainer, IsDS, newOne.SystemAcl, true ); } else { _securityDescriptor.SystemAcl = null; } // carry forward the SACL related control flags _securityDescriptor.UpdateControlFlags(SACL_CONTROL_FLAGS, (ControlFlags)(newOne.ControlFlags & SACL_CONTROL_FLAGS)); } if (( includeSections & AccessControlSections.Access ) != 0 ) { _daclModified = true; if ( newOne.DiscretionaryAcl != null ) { _securityDescriptor.DiscretionaryAcl = new DiscretionaryAcl( IsContainer, IsDS, newOne.DiscretionaryAcl, true ); } else { _securityDescriptor.DiscretionaryAcl = null; } // by the following property set, the _securityDescriptor's control flags // may contains DACL present flag. That needs to be carried forward! Therefore, we OR // the current _securityDescriptor.s DACL present flag. ControlFlags daclFlag = (_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent); _securityDescriptor.UpdateControlFlags(DACL_CONTROL_FLAGS, (ControlFlags)((newOne.ControlFlags | daclFlag) & DACL_CONTROL_FLAGS)); } } #endregion #region Protected Properties and Methods protected void ReadLock() { _lock.AcquireReaderLock( -1 ); } protected void ReadUnlock() { _lock.ReleaseReaderLock(); } protected void WriteLock() { _lock.AcquireWriterLock( -1 ); } protected void WriteUnlock() { _lock.ReleaseWriterLock(); } protected bool OwnerModified { get { if (!( _lock.IsReaderLockHeld || _lock.IsWriterLockHeld )) { throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_MustLockForReadOrWrite" )); } return _ownerModified; } set { if ( !_lock.IsWriterLockHeld ) { throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_MustLockForWrite" )); } _ownerModified = value; } } protected bool GroupModified { get { if (!( _lock.IsReaderLockHeld || _lock.IsWriterLockHeld )) { throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_MustLockForReadOrWrite" )); } return _groupModified; } set { if ( !_lock.IsWriterLockHeld ) { throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_MustLockForWrite" )); } _groupModified = value; } } protected bool AuditRulesModified { get { if (!( _lock.IsReaderLockHeld || _lock.IsWriterLockHeld )) { throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_MustLockForReadOrWrite" )); } return _saclModified; } set { if ( !_lock.IsWriterLockHeld ) { throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_MustLockForWrite" )); } _saclModified = value; } } protected bool AccessRulesModified { get { if (!( _lock.IsReaderLockHeld || _lock.IsWriterLockHeld )) { throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_MustLockForReadOrWrite" )); } return _daclModified; } set { if ( !_lock.IsWriterLockHeld ) { throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_MustLockForWrite" )); } _daclModified = value; } } protected bool IsContainer { get { return _securityDescriptor.IsContainer; } } protected bool IsDS { get { return _securityDescriptor.IsDS; } } // // Persists the changes made to the object // // This overloaded method takes a name of an existing object // protected virtual void Persist( string name, AccessControlSections includeSections ) { throw new NotImplementedException(); } // // if Persist (by name) is implemented, then this function will also try to enable take ownership // privilege while persisting if the enableOwnershipPrivilege is true. // Integrators can override it if this is not desired. // [System.Security.SecuritySafeCritical] // auto-generated #if FEATURE_CORRUPTING_EXCEPTIONS [HandleProcessCorruptedStateExceptions] // #endif // FEATURE_CORRUPTING_EXCEPTIONS protected virtual void Persist(bool enableOwnershipPrivilege, string name, AccessControlSections includeSections ) { Privilege ownerPrivilege = null; // Ensure that the finally block will execute RuntimeHelpers.PrepareConstrainedRegions(); try { if (enableOwnershipPrivilege) { ownerPrivilege = new Privilege(Privilege.TakeOwnership); try { ownerPrivilege.Enable(); } catch (PrivilegeNotHeldException) { // we will ignore this exception and press on just in case this is a remote resource } } Persist(name, includeSections); } catch { // protection against exception filter-based luring attacks if ( ownerPrivilege != null ) { ownerPrivilege.Revert(); } throw; } finally { if (ownerPrivilege != null) { ownerPrivilege.Revert(); } } } // // Persists the changes made to the object // // This overloaded method takes a handle to an existing object // [System.Security.SecuritySafeCritical] // auto-generated protected virtual void Persist( SafeHandle handle, AccessControlSections includeSections ) { throw new NotImplementedException(); } #endregion #region Public Methods // // Sets and retrieves the owner of this object // public IdentityReference GetOwner( System.Type targetType ) { ReadLock(); try { if ( _securityDescriptor.Owner == null ) { return null; } return _securityDescriptor.Owner.Translate( targetType ); } finally { ReadUnlock(); } } public void SetOwner( IdentityReference identity ) { if ( identity == null ) { throw new ArgumentNullException( "identity" ); } Contract.EndContractBlock(); WriteLock(); try { _securityDescriptor.Owner = identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier; _ownerModified = true; } finally { WriteUnlock(); } } // // Sets and retrieves the group of this object // public IdentityReference GetGroup( System.Type targetType ) { ReadLock(); try { if ( _securityDescriptor.Group == null ) { return null; } return _securityDescriptor.Group.Translate( targetType ); } finally { ReadUnlock(); } } public void SetGroup( IdentityReference identity ) { if ( identity == null ) { throw new ArgumentNullException( "identity" ); } Contract.EndContractBlock(); WriteLock(); try { _securityDescriptor.Group = identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier; _groupModified = true; } finally { WriteUnlock(); } } public virtual void PurgeAccessRules( IdentityReference identity ) { if ( identity == null ) { throw new ArgumentNullException( "identity" ); } Contract.EndContractBlock(); WriteLock(); try { _securityDescriptor.PurgeAccessControl( identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier ); _daclModified = true; } finally { WriteUnlock(); } } public virtual void PurgeAuditRules(IdentityReference identity) { if ( identity == null ) { throw new ArgumentNullException( "identity" ); } Contract.EndContractBlock(); WriteLock(); try { _securityDescriptor.PurgeAudit( identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier ); _saclModified = true; } finally { WriteUnlock(); } } public bool AreAccessRulesProtected { get { ReadLock(); try { return (( _securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected ) != 0 ); } finally { ReadUnlock(); } } } public void SetAccessRuleProtection( bool isProtected, bool preserveInheritance ) { WriteLock(); try { _securityDescriptor.SetDiscretionaryAclProtection( isProtected, preserveInheritance ); _daclModified = true; } finally { WriteUnlock(); } } public bool AreAuditRulesProtected { get { ReadLock(); try { return (( _securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected ) != 0 ); } finally { ReadUnlock(); } } } public void SetAuditRuleProtection( bool isProtected, bool preserveInheritance ) { WriteLock(); try { _securityDescriptor.SetSystemAclProtection( isProtected, preserveInheritance ); _saclModified = true; } finally { WriteUnlock(); } } public bool AreAccessRulesCanonical { get { ReadLock(); try { return _securityDescriptor.IsDiscretionaryAclCanonical; } finally { ReadUnlock(); } } } public bool AreAuditRulesCanonical { get { ReadLock(); try { return _securityDescriptor.IsSystemAclCanonical; } finally { ReadUnlock(); } } } public static bool IsSddlConversionSupported() { return true; // SDDL to binary conversions are supported on Windows 2000 and higher } public string GetSecurityDescriptorSddlForm( AccessControlSections includeSections ) { ReadLock(); try { return _securityDescriptor.GetSddlForm( includeSections ); } finally { ReadUnlock(); } } public void SetSecurityDescriptorSddlForm( string sddlForm ) { SetSecurityDescriptorSddlForm( sddlForm, AccessControlSections.All ); } public void SetSecurityDescriptorSddlForm( string sddlForm, AccessControlSections includeSections ) { if ( sddlForm == null ) { throw new ArgumentNullException( "sddlForm" ); } if (( includeSections & AccessControlSections.All ) == 0 ) { throw new ArgumentException( Environment.GetResourceString( "Arg_EnumAtLeastOneFlag" ), "includeSections" ); } Contract.EndContractBlock(); WriteLock(); try { UpdateWithNewSecurityDescriptor( new RawSecurityDescriptor( sddlForm ), includeSections ); } finally { WriteUnlock(); } } public byte[] GetSecurityDescriptorBinaryForm() { ReadLock(); try { byte[] result = new byte[_securityDescriptor.BinaryLength]; _securityDescriptor.GetBinaryForm( result, 0 ); return result; } finally { ReadUnlock(); } } public void SetSecurityDescriptorBinaryForm( byte[] binaryForm ) { SetSecurityDescriptorBinaryForm( binaryForm, AccessControlSections.All ); } public void SetSecurityDescriptorBinaryForm( byte[] binaryForm, AccessControlSections includeSections ) { if ( binaryForm == null ) { throw new ArgumentNullException( "binaryForm" ); } if (( includeSections & AccessControlSections.All ) == 0 ) { throw new ArgumentException( Environment.GetResourceString( "Arg_EnumAtLeastOneFlag" ), "includeSections" ); } Contract.EndContractBlock(); WriteLock(); try { UpdateWithNewSecurityDescriptor( new RawSecurityDescriptor( binaryForm, 0 ), includeSections ); } finally { WriteUnlock(); } } public abstract Type AccessRightType { get; } public abstract Type AccessRuleType { get; } public abstract Type AuditRuleType { get; } protected abstract bool ModifyAccess( AccessControlModification modification, AccessRule rule, out bool modified); protected abstract bool ModifyAudit( AccessControlModification modification, AuditRule rule, out bool modified ); public virtual bool ModifyAccessRule(AccessControlModification modification, AccessRule rule, out bool modified) { if ( rule == null ) { throw new ArgumentNullException( "rule" ); } if ( !this.AccessRuleType.IsAssignableFrom(rule.GetType()) ) { throw new ArgumentException( Environment.GetResourceString("AccessControl_InvalidAccessRuleType"), "rule"); } Contract.EndContractBlock(); WriteLock(); try { return ModifyAccess(modification, rule, out modified); } finally { WriteUnlock(); } } public virtual bool ModifyAuditRule(AccessControlModification modification, AuditRule rule, out bool modified) { if ( rule == null ) { throw new ArgumentNullException( "rule" ); } if ( !this.AuditRuleType.IsAssignableFrom(rule.GetType()) ) { throw new ArgumentException( Environment.GetResourceString("AccessControl_InvalidAuditRuleType"), "rule"); } Contract.EndContractBlock(); WriteLock(); try { return ModifyAudit(modification, rule, out modified); } finally { WriteUnlock(); } } public abstract AccessRule AccessRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type ); public abstract AuditRule AuditRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags ); #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Globalization; namespace System.Collections.Immutable { /// <content> /// Contains the inner <see cref="ImmutableDictionary{TKey, TValue}.HashBucket"/> struct. /// </content> public partial class ImmutableDictionary<TKey, TValue> { /// <summary> /// Contains all the key/values in the collection that hash to the same value. /// </summary> internal struct HashBucket : IEnumerable<KeyValuePair<TKey, TValue>>, IEquatable<HashBucket> { /// <summary> /// One of the values in this bucket. /// </summary> private readonly KeyValuePair<TKey, TValue> _firstValue; /// <summary> /// Any other elements that hash to the same value. /// </summary> /// <value> /// This is null if and only if the entire bucket is empty (including <see cref="_firstValue"/>). /// It's empty if <see cref="_firstValue"/> has an element but no additional elements. /// </value> private readonly ImmutableList<KeyValuePair<TKey, TValue>>.Node _additionalElements; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}.HashBucket"/> struct. /// </summary> /// <param name="firstElement">The first element.</param> /// <param name="additionalElements">The additional elements.</param> private HashBucket(KeyValuePair<TKey, TValue> firstElement, ImmutableList<KeyValuePair<TKey, TValue>>.Node additionalElements = null) { _firstValue = firstElement; _additionalElements = additionalElements ?? ImmutableList<KeyValuePair<TKey, TValue>>.Node.EmptyNode; } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> internal bool IsEmpty { get { return _additionalElements == null; } } /// <summary> /// Gets the first value in this bucket. /// </summary> internal KeyValuePair<TKey, TValue> FirstValue { get { if (this.IsEmpty) { throw new InvalidOperationException(); } return _firstValue; } } /// <summary> /// Gets the list of additional (hash collision) elements. /// </summary> internal ImmutableList<KeyValuePair<TKey, TValue>>.Node AdditionalElements { get { return _additionalElements; } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <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> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Throws an exception to catch any errors in comparing <see cref="HashBucket"/> instances. /// </summary> bool IEquatable<HashBucket>.Equals(HashBucket other) { // This should never be called, as hash buckets don't know how to equate themselves. throw new NotSupportedException(); } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key to add.</param> /// <param name="value">The value to add.</param> /// <param name="keyOnlyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="behavior">The intended behavior for certain cases that may come up during the operation.</param> /// <param name="result">A description of the effect was on adding an element to this <see cref="HashBucket"/>.</param> /// <returns>A new <see cref="HashBucket"/> that contains the added value and any values already held by this <see cref="HashBucket"/>.</returns> internal HashBucket Add(TKey key, TValue value, IEqualityComparer<KeyValuePair<TKey, TValue>> keyOnlyComparer, IEqualityComparer<TValue> valueComparer, KeyCollisionBehavior behavior, out OperationResult result) { var kv = new KeyValuePair<TKey, TValue>(key, value); if (this.IsEmpty) { result = OperationResult.SizeChanged; return new HashBucket(kv); } if (keyOnlyComparer.Equals(kv, _firstValue)) { switch (behavior) { case KeyCollisionBehavior.SetValue: result = OperationResult.AppliedWithoutSizeChange; return new HashBucket(kv, _additionalElements); case KeyCollisionBehavior.Skip: result = OperationResult.NoChangeRequired; return this; case KeyCollisionBehavior.ThrowIfValueDifferent: if (!valueComparer.Equals(_firstValue.Value, value)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key)); } result = OperationResult.NoChangeRequired; return this; case KeyCollisionBehavior.ThrowAlways: throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key)); default: throw new InvalidOperationException(); // unreachable } } int keyCollisionIndex = _additionalElements.IndexOf(kv, keyOnlyComparer); if (keyCollisionIndex < 0) { result = OperationResult.SizeChanged; return new HashBucket(_firstValue, _additionalElements.Add(kv)); } else { switch (behavior) { case KeyCollisionBehavior.SetValue: result = OperationResult.AppliedWithoutSizeChange; return new HashBucket(_firstValue, _additionalElements.ReplaceAt(keyCollisionIndex, kv)); case KeyCollisionBehavior.Skip: result = OperationResult.NoChangeRequired; return this; case KeyCollisionBehavior.ThrowIfValueDifferent: var existingEntry = _additionalElements[keyCollisionIndex]; if (!valueComparer.Equals(existingEntry.Value, value)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key)); } result = OperationResult.NoChangeRequired; return this; case KeyCollisionBehavior.ThrowAlways: throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key)); default: throw new InvalidOperationException(); // unreachable } } } /// <summary> /// Removes the specified value if it exists in the collection. /// </summary> /// <param name="key">The key to remove.</param> /// <param name="keyOnlyComparer">The equality comparer.</param> /// <param name="result">A description of the effect was on adding an element to this <see cref="HashBucket"/>.</param> /// <returns>A new <see cref="HashBucket"/> that does not contain the removed value and any values already held by this <see cref="HashBucket"/>.</returns> internal HashBucket Remove(TKey key, IEqualityComparer<KeyValuePair<TKey, TValue>> keyOnlyComparer, out OperationResult result) { if (this.IsEmpty) { result = OperationResult.NoChangeRequired; return this; } var kv = new KeyValuePair<TKey, TValue>(key, default(TValue)); if (keyOnlyComparer.Equals(_firstValue, kv)) { if (_additionalElements.IsEmpty) { result = OperationResult.SizeChanged; return new HashBucket(); } else { // We can promote any element from the list into the first position, but it's most efficient // to remove the root node in the binary tree that implements the list. int indexOfRootNode = _additionalElements.Left.Count; result = OperationResult.SizeChanged; return new HashBucket(_additionalElements.Key, _additionalElements.RemoveAt(indexOfRootNode)); } } int index = _additionalElements.IndexOf(kv, keyOnlyComparer); if (index < 0) { result = OperationResult.NoChangeRequired; return this; } else { result = OperationResult.SizeChanged; return new HashBucket(_firstValue, _additionalElements.RemoveAt(index)); } } /// <summary> /// Gets the value for the given key in the collection if one exists.. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="keyOnlyComparer">The key comparer.</param> /// <param name="value">The value for the given key.</param> /// <returns>A value indicating whether the key was found.</returns> internal bool TryGetValue(TKey key, IEqualityComparer<KeyValuePair<TKey, TValue>> keyOnlyComparer, out TValue value) { if (this.IsEmpty) { value = default(TValue); return false; } var kv = new KeyValuePair<TKey, TValue>(key, default(TValue)); if (keyOnlyComparer.Equals(_firstValue, kv)) { value = _firstValue.Value; return true; } var index = _additionalElements.IndexOf(kv, keyOnlyComparer); if (index < 0) { value = default(TValue); return false; } value = _additionalElements[index].Value; return true; } /// <summary> /// Searches the dictionary for a given key and returns the equal key it finds, if any. /// </summary> /// <param name="equalKey">The key to search for.</param> /// <param name="keyOnlyComparer">The key comparer.</param> /// <param name="actualKey">The key from the dictionary that the search found, or <paramref name="equalKey"/> if the search yielded no match.</param> /// <returns>A value indicating whether the search was successful.</returns> /// <remarks> /// This can be useful when you want to reuse a previously stored reference instead of /// a newly constructed one (so that more sharing of references can occur) or to look up /// the canonical value, or a value that has more complete data than the value you currently have, /// although their comparer functions indicate they are equal. /// </remarks> internal bool TryGetKey(TKey equalKey, IEqualityComparer<KeyValuePair<TKey, TValue>> keyOnlyComparer, out TKey actualKey) { if (this.IsEmpty) { actualKey = equalKey; return false; } var kv = new KeyValuePair<TKey, TValue>(equalKey, default(TValue)); if (keyOnlyComparer.Equals(_firstValue, kv)) { actualKey = _firstValue.Key; return true; } var index = _additionalElements.IndexOf(kv, keyOnlyComparer); if (index < 0) { actualKey = equalKey; return false; } actualKey = _additionalElements[index].Key; return true; } /// <summary> /// Freezes this instance so that any further mutations require new memory allocations. /// </summary> internal void Freeze() { if (_additionalElements != null) { _additionalElements.Freeze(); } } /// <summary> /// Enumerates all the elements in this instance. /// </summary> internal struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable { /// <summary> /// The bucket being enumerated. /// </summary> private readonly HashBucket _bucket; /// <summary> /// The current position of this enumerator. /// </summary> private Position _currentPosition; /// <summary> /// The enumerator that represents the current position over the <see cref="_additionalElements"/> of the <see cref="HashBucket"/>. /// </summary> private ImmutableList<KeyValuePair<TKey, TValue>>.Enumerator _additionalEnumerator; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}.HashBucket.Enumerator"/> struct. /// </summary> /// <param name="bucket">The bucket.</param> internal Enumerator(HashBucket bucket) { _bucket = bucket; _currentPosition = Position.BeforeFirst; _additionalEnumerator = default(ImmutableList<KeyValuePair<TKey, TValue>>.Enumerator); } /// <summary> /// Describes the positions the enumerator state machine may be in. /// </summary> private enum Position { /// <summary> /// The first element has not yet been moved to. /// </summary> BeforeFirst, /// <summary> /// We're at the <see cref="_firstValue"/> of the containing bucket. /// </summary> First, /// <summary> /// We're enumerating the <see cref="_additionalElements"/> in the bucket. /// </summary> Additional, /// <summary> /// The end of enumeration has been reached. /// </summary> End, } /// <summary> /// Gets the current element. /// </summary> object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Gets the current element. /// </summary> public KeyValuePair<TKey, TValue> Current { get { switch (_currentPosition) { case Position.First: return _bucket._firstValue; case Position.Additional: return _additionalEnumerator.Current; default: throw new InvalidOperationException(); } } } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection. /// </returns> /// <exception cref="InvalidOperationException">The collection was modified after the enumerator was created. </exception> public bool MoveNext() { if (_bucket.IsEmpty) { _currentPosition = Position.End; return false; } switch (_currentPosition) { case Position.BeforeFirst: _currentPosition = Position.First; return true; case Position.First: if (_bucket._additionalElements.IsEmpty) { _currentPosition = Position.End; return false; } _currentPosition = Position.Additional; _additionalEnumerator = new ImmutableList<KeyValuePair<TKey, TValue>>.Enumerator(_bucket._additionalElements); return _additionalEnumerator.MoveNext(); case Position.Additional: return _additionalEnumerator.MoveNext(); case Position.End: return false; default: throw new InvalidOperationException(); } } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> /// <exception cref="InvalidOperationException">The collection was modified after the enumerator was created. </exception> public void Reset() { // We can safely dispose of the additional enumerator because if the client reuses this enumerator // we'll acquire a new one anyway (and so for that matter we should be sure to dispose of this). _additionalEnumerator.Dispose(); _currentPosition = Position.BeforeFirst; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { _additionalEnumerator.Dispose(); } } } } }
/* * 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 log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.Reflection; namespace OpenSim.Region.CoreModules { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SunModule")] public class SunModule : ISunModule { /// <summary> /// Note: Sun Hour can be a little deceaving. Although it's based on a 24 hour clock /// it is not based on ~06:00 == Sun Rise. Rather it is based on 00:00 being sun-rise. /// </summary> private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // // Global Constants used to determine where in the sky the sun is // private const double m_SeasonalTilt = 0.03 * Math.PI; // A daily shift of approximately 1.7188 degrees private const double m_AverageTilt = -0.25 * Math.PI; // A 45 degree tilt private const double m_SunCycle = 2.0D * Math.PI; // A perfect circle measured in radians private const double m_SeasonalCycle = 2.0D * Math.PI; // Ditto // // Per Region Values // private bool ready = false; // This solves a chick before the egg problem // the local SunFixedHour and SunFixed variables MUST be updated // at least once with the proper Region Settings before we start // updating those region settings in GenSunPos() private bool receivedEstateToolsSunUpdate = false; // Sun's position information is updated and sent to clients every m_UpdateInterval frames private int m_UpdateInterval = 0; // Number of real time hours per virtual day private double m_DayLengthHours = 0; // Number of virtual days to a virtual year private int m_YearLengthDays = 0; // Ratio of Daylight hours to Night time hours. This is accomplished by shifting the // sun's orbit above the horizon private double m_HorizonShift = 0; // Used to scale current and positional time to adjust length of an hour during day vs night. private double m_DayTimeSunHourScale; // private double m_longitude = 0; // private double m_latitude = 0; // Configurable defaults Defaults close to SL private int d_frame_mod = 100; // Every 10 seconds (actually less) private double d_day_length = 4; // A VW day is 4 RW hours long private int d_year_length = 60; // There are 60 VW days in a VW year private double d_day_night = 0.5; // axis offset: Default Hoizon shift to try and closely match the sun model in LL Viewer private double d_DayTimeSunHourScale = 0.5; // Day/Night hours are equal // private double d_longitude = -73.53; // private double d_latitude = 41.29; // Frame counter private uint m_frame = 0; // Cached Scene reference private Scene m_scene = null; // Calculated Once in the lifetime of a region private long TicksToEpoch; // Elapsed time for 1/1/1970 private uint SecondsPerSunCycle; // Length of a virtual day in RW seconds private uint SecondsPerYear; // Length of a virtual year in RW seconds private double SunSpeed; // Rate of passage in radians/second private double SeasonSpeed; // Rate of change for seasonal effects // private double HoursToRadians; // Rate of change for seasonal effects private long TicksUTCOffset = 0; // seconds offset from UTC // Calculated every update private float OrbitalPosition; // Orbital placement at a point in time private double HorizonShift; // Axis offset to skew day and night private double TotalDistanceTravelled; // Distance since beginning of time (in radians) private double SeasonalOffset; // Seaonal variation of tilt private float Magnitude; // Normal tilt // private double VWTimeRatio; // VW time as a ratio of real time // Working values private Vector3 Position = Vector3.Zero; private Vector3 Velocity = Vector3.Zero; private Quaternion Tilt = new Quaternion(1.0f, 0.0f, 0.0f, 0.0f); // Used to fix the sun in the sky so it doesn't move based on current time private bool m_SunFixed = false; private float m_SunFixedHour = 0f; private const int TICKS_PER_SECOND = 10000000; private ulong m_CurrentTimeOffset = 0; // Current time in elapsed seconds since Jan 1st 1970 private ulong CurrentTime { get { ulong ctime = (ulong)(((DateTime.Now.Ticks) - TicksToEpoch + TicksUTCOffset) / TICKS_PER_SECOND); return ctime + m_CurrentTimeOffset; } } // Time in seconds since UTC to use to calculate sun position. ulong PosTime = 0; /// <summary> /// Calculate the sun's orbital position and its velocity. /// </summary> private void GenSunPos() { // Time in seconds since UTC to use to calculate sun position. PosTime = CurrentTime; if (m_SunFixed) { // SunFixedHour represents the "hour of day" we would like // It's represented in 24hr time, with 0 hour being sun-rise // Because our day length is probably not 24hrs {LL is 6} we need to do a bit of math // Determine the current "day" from current time, so we can use "today" // to determine Seasonal Tilt and what'not // Integer math rounded is on purpose to drop fractional day, determines number // of virtual days since Epoch PosTime = CurrentTime / SecondsPerSunCycle; // Since we want number of seconds since Epoch, multiply back up PosTime *= SecondsPerSunCycle; // Then offset by the current Fixed Sun Hour // Fixed Sun Hour needs to be scaled to reflect the user configured Seconds Per Sun Cycle PosTime += (ulong)((m_SunFixedHour / 24.0) * (ulong)SecondsPerSunCycle); } else { if (m_DayTimeSunHourScale != 0.5f) { ulong CurDaySeconds = CurrentTime % SecondsPerSunCycle; double CurDayPercentage = (double)CurDaySeconds / SecondsPerSunCycle; ulong DayLightSeconds = (ulong)(m_DayTimeSunHourScale * SecondsPerSunCycle); ulong NightSeconds = SecondsPerSunCycle - DayLightSeconds; PosTime = CurrentTime / SecondsPerSunCycle; PosTime *= SecondsPerSunCycle; if (CurDayPercentage < 0.5) { PosTime += (ulong)((CurDayPercentage / .5) * DayLightSeconds); } else { PosTime += DayLightSeconds; PosTime += (ulong)(((CurDayPercentage - 0.5) / .5) * NightSeconds); } } } TotalDistanceTravelled = SunSpeed * PosTime; // distance measured in radians OrbitalPosition = (float)(TotalDistanceTravelled % m_SunCycle); // position measured in radians // TotalDistanceTravelled += HoursToRadians-(0.25*Math.PI)*Math.Cos(HoursToRadians)-OrbitalPosition; // OrbitalPosition = (float) (TotalDistanceTravelled%SunCycle); SeasonalOffset = SeasonSpeed * PosTime; // Present season determined as total radians travelled around season cycle Tilt.W = (float)(m_AverageTilt + (m_SeasonalTilt * Math.Sin(SeasonalOffset))); // Calculate seasonal orbital N/S tilt // m_log.Debug("[SUN] Total distance travelled = "+TotalDistanceTravelled+", present position = "+OrbitalPosition+"."); // m_log.Debug("[SUN] Total seasonal progress = "+SeasonalOffset+", present tilt = "+Tilt.W+"."); // The sun rotates about the Z axis Position.X = (float)Math.Cos(-TotalDistanceTravelled); Position.Y = (float)Math.Sin(-TotalDistanceTravelled); Position.Z = 0; // For interest we rotate it slightly about the X access. // Celestial tilt is a value that ranges .025 Position *= Tilt; // Finally we shift the axis so that more of the // circle is above the horizon than below. This // makes the nights shorter than the days. Position = Vector3.Normalize(Position); Position.Z = Position.Z + (float)HorizonShift; Position = Vector3.Normalize(Position); // m_log.Debug("[SUN] Position("+Position.X+","+Position.Y+","+Position.Z+")"); Velocity.X = 0; Velocity.Y = 0; Velocity.Z = (float)SunSpeed; // Correct angular velocity to reflect the seasonal rotation Magnitude = Position.Length(); if (m_SunFixed) { Velocity.X = 0; Velocity.Y = 0; Velocity.Z = 0; } else { Velocity = (Velocity * Tilt) * (1.0f / Magnitude); } // TODO: Decouple this, so we can get rid of Linden Hour info // Update Region with new Sun Vector // set estate settings for region access to sun position if (receivedEstateToolsSunUpdate) { m_scene.RegionInfo.RegionSettings.SunVector = Position; } } private float GetCurrentTimeAsLindenSunHour() { float curtime = m_SunFixed ? m_SunFixedHour : GetCurrentSunHour(); return (curtime + 6.0f) % 24.0f; } #region INonSharedRegion Methods // Called immediately after the module is loaded for a given region // i.e. Immediately after instance creation. public void Initialise(IConfigSource config) { m_frame = 0; // This one puts an entry in the main help screen // m_scene.AddCommand("Regions", this, "sun", "sun", "Usage: sun [param] [value] - Get or Update Sun module paramater", null); TimeZone local = TimeZone.CurrentTimeZone; TicksUTCOffset = local.GetUtcOffset(local.ToLocalTime(DateTime.Now)).Ticks; m_log.DebugFormat("[SUN]: localtime offset is {0}", TicksUTCOffset); // Align ticks with Second Life TicksToEpoch = new DateTime(1970, 1, 1).Ticks; // Just in case they don't have the stanzas try { // Mode: determines how the sun is handled // m_latitude = config.Configs["Sun"].GetDouble("latitude", d_latitude); // Mode: determines how the sun is handled // m_longitude = config.Configs["Sun"].GetDouble("longitude", d_longitude); // Year length in days m_YearLengthDays = config.Configs["Sun"].GetInt("year_length", d_year_length); // Day length in decimal hours m_DayLengthHours = config.Configs["Sun"].GetDouble("day_length", d_day_length); // Horizon shift, this is used to shift the sun's orbit, this affects the day / night ratio // must hard code to ~.5 to match sun position in LL based viewers m_HorizonShift = config.Configs["Sun"].GetDouble("day_night_offset", d_day_night); // Scales the sun hours 0...12 vs 12...24, essentially makes daylight hours longer/shorter vs nighttime hours m_DayTimeSunHourScale = config.Configs["Sun"].GetDouble("day_time_sun_hour_scale", d_DayTimeSunHourScale); // Update frequency in frames m_UpdateInterval = config.Configs["Sun"].GetInt("update_interval", d_frame_mod); } catch (Exception e) { m_log.Debug("[SUN]: Configuration access failed, using defaults. Reason: " + e.Message); m_YearLengthDays = d_year_length; m_DayLengthHours = d_day_length; m_HorizonShift = d_day_night; m_UpdateInterval = d_frame_mod; m_DayTimeSunHourScale = d_DayTimeSunHourScale; // m_latitude = d_latitude; // m_longitude = d_longitude; } SecondsPerSunCycle = (uint) (m_DayLengthHours * 60 * 60); SecondsPerYear = (uint) (SecondsPerSunCycle*m_YearLengthDays); // Ration of real-to-virtual time // VWTimeRatio = 24/m_day_length; // Speed of rotation needed to complete a cycle in the // designated period (day and season) SunSpeed = m_SunCycle/SecondsPerSunCycle; SeasonSpeed = m_SeasonalCycle/SecondsPerYear; // Horizon translation HorizonShift = m_HorizonShift; // Z axis translation // HoursToRadians = (SunCycle/24)*VWTimeRatio; m_log.Debug("[SUN]: Initialization completed. Day is " + SecondsPerSunCycle + " seconds, and year is " + m_YearLengthDays + " days"); m_log.Debug("[SUN]: Axis offset is " + m_HorizonShift); m_log.Debug("[SUN]: Percentage of time for daylight " + m_DayTimeSunHourScale); m_log.Debug("[SUN]: Positional data updated every " + m_UpdateInterval + " frames"); } public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene scene) { m_scene = scene; // Insert our event handling hooks scene.EventManager.OnFrame += SunUpdate; scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel; scene.EventManager.OnEstateToolsSunUpdate += EstateToolsSunUpdate; scene.EventManager.OnGetCurrentTimeAsLindenSunHour += GetCurrentTimeAsLindenSunHour; scene.RegisterModuleInterface<ISunModule>(this); // This one enables the ability to type just "sun" without any parameters // m_scene.AddCommand("Regions", this, "sun", "", "", HandleSunConsoleCommand); foreach (KeyValuePair<string, string> kvp in GetParamList()) { string sunCommand = string.Format("sun {0}", kvp.Key); m_scene.AddCommand("Regions", this, sunCommand, string.Format("{0} [<value>]", sunCommand), kvp.Value, "", HandleSunConsoleCommand); } m_scene.AddCommand("Regions", this, "sun help", "sun help", "list parameters that can be changed", "", HandleSunConsoleCommand); m_scene.AddCommand("Regions", this, "sun list", "sun list", "list parameters that can be changed", "", HandleSunConsoleCommand); ready = true; } public void RemoveRegion(Scene scene) { ready = false; // Remove our hooks m_scene.EventManager.OnFrame -= SunUpdate; m_scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel; m_scene.EventManager.OnEstateToolsSunUpdate -= EstateToolsSunUpdate; m_scene.EventManager.OnGetCurrentTimeAsLindenSunHour -= GetCurrentTimeAsLindenSunHour; } public void RegionLoaded(Scene scene) { } public void Close() { } public string Name { get { return "SunModule"; } } #endregion #region EventManager Events public void SunToClient(IClientAPI client) { if (ready) { if (m_SunFixed) { // m_log.DebugFormat("[SUN]: Fixed SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", // m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString()); client.SendSunPos(Position, Velocity, PosTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition); } else { // m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", // m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString()); client.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition); } } } public void SunUpdate() { if (((m_frame++ % m_UpdateInterval) != 0) || !ready || m_SunFixed || !receivedEstateToolsSunUpdate) return; GenSunPos(); // Generate shared values once SunUpdateToAllClients(); } /// <summary> /// When an avatar enters the region, it's probably a good idea to send them the current sun info /// </summary> /// <param name="avatar"></param> /// <param name="localLandID"></param> /// <param name="regionID"></param> private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID) { SunToClient(avatar.ControllingClient); } public void EstateToolsSunUpdate(ulong regionHandle) { if (m_scene.RegionInfo.RegionHandle == regionHandle) { float sunFixedHour; bool fixedSun; if (m_scene.RegionInfo.RegionSettings.UseEstateSun) { sunFixedHour = (float)m_scene.RegionInfo.EstateSettings.SunPosition; fixedSun = m_scene.RegionInfo.EstateSettings.FixedSun; } else { sunFixedHour = (float)m_scene.RegionInfo.RegionSettings.SunPosition - 6.0f; fixedSun = m_scene.RegionInfo.RegionSettings.FixedSun; } // Must limit the Sun Hour to 0 ... 24 while (sunFixedHour > 24.0f) sunFixedHour -= 24; while (sunFixedHour < 0) sunFixedHour += 24; m_SunFixedHour = sunFixedHour; m_SunFixed = fixedSun; // m_log.DebugFormat("[SUN]: Sun Settings Update: Fixed Sun? : {0}", m_SunFixed.ToString()); // m_log.DebugFormat("[SUN]: Sun Settings Update: Sun Hour : {0}", m_SunFixedHour.ToString()); receivedEstateToolsSunUpdate = true; // Generate shared values GenSunPos(); // When sun settings are updated, we should update all clients with new settings. SunUpdateToAllClients(); // m_log.DebugFormat("[SUN]: PosTime : {0}", PosTime.ToString()); } } #endregion private void SunUpdateToAllClients() { m_scene.ForEachRootClient(delegate(IClientAPI client) { SunToClient(client); }); } #region ISunModule Members public double GetSunParameter(string param) { switch (param.ToLower()) { case "year_length": return m_YearLengthDays; case "day_length": return m_DayLengthHours; case "day_night_offset": return m_HorizonShift; case "day_time_sun_hour_scale": return m_DayTimeSunHourScale; case "update_interval": return m_UpdateInterval; case "current_time": return GetCurrentTimeAsLindenSunHour(); default: throw new Exception("Unknown sun parameter."); } } public void SetSunParameter(string param, double value) { switch (param) { case "year_length": m_YearLengthDays = (int)value; SecondsPerYear = (uint) (SecondsPerSunCycle*m_YearLengthDays); SeasonSpeed = m_SeasonalCycle/SecondsPerYear; break; case "day_length": m_DayLengthHours = value; SecondsPerSunCycle = (uint) (m_DayLengthHours * 60 * 60); SecondsPerYear = (uint) (SecondsPerSunCycle*m_YearLengthDays); SunSpeed = m_SunCycle/SecondsPerSunCycle; SeasonSpeed = m_SeasonalCycle/SecondsPerYear; break; case "day_night_offset": m_HorizonShift = value; HorizonShift = m_HorizonShift; break; case "day_time_sun_hour_scale": m_DayTimeSunHourScale = value; break; case "update_interval": m_UpdateInterval = (int)value; break; case "current_time": value = (value + 18.0) % 24.0; // set the current offset so that the effective sun time is the parameter m_CurrentTimeOffset = 0; // clear this first so we use raw time m_CurrentTimeOffset = (ulong)(SecondsPerSunCycle * value/ 24.0) - (CurrentTime % SecondsPerSunCycle); break; default: throw new Exception("Unknown sun parameter."); } // Generate shared values GenSunPos(); // When sun settings are updated, we should update all clients with new settings. SunUpdateToAllClients(); } public float GetCurrentSunHour() { float ticksleftover = CurrentTime % SecondsPerSunCycle; return (24.0f * (ticksleftover / SecondsPerSunCycle)); } #endregion public void HandleSunConsoleCommand(string module, string[] cmdparams) { if (m_scene.ConsoleScene() == null) { // FIXME: If console region is root then this will be printed by every module. Currently, there is no // way to prevent this, short of making the entire module shared (which is complete overkill). // One possibility is to return a bool to signal whether the module has completely handled the command m_log.InfoFormat("[Sun]: Please change to a specific region in order to set Sun parameters."); return; } if (m_scene.ConsoleScene() != m_scene) { m_log.InfoFormat("[Sun]: Console Scene is not my scene."); return; } m_log.InfoFormat("[Sun]: Processing command."); foreach (string output in ParseCmdParams(cmdparams)) { MainConsole.Instance.Output(output); } } private Dictionary<string, string> GetParamList() { Dictionary<string, string> Params = new Dictionary<string, string>(); Params.Add("year_length", "number of days to a year"); Params.Add("day_length", "number of hours to a day"); Params.Add("day_night_offset", "induces a horizon shift"); Params.Add("update_interval", "how often to update the sun's position in frames"); Params.Add("day_time_sun_hour_scale", "scales day light vs nite hours to change day/night ratio"); Params.Add("current_time", "time in seconds of the simulator"); return Params; } private List<string> ParseCmdParams(string[] args) { List<string> Output = new List<string>(); if ((args.Length == 1) || (args[1].ToLower() == "help") || (args[1].ToLower() == "list")) { Output.Add("The following parameters can be changed or viewed:"); foreach (KeyValuePair<string, string> kvp in GetParamList()) { Output.Add(String.Format("{0} - {1}",kvp.Key, kvp.Value)); } return Output; } if (args.Length == 2) { try { double value = GetSunParameter(args[1]); Output.Add(String.Format("Parameter {0} is {1}.", args[1], value.ToString())); } catch (Exception) { Output.Add(String.Format("Unknown parameter {0}.", args[1])); } } else if (args.Length == 3) { double value = 0.0; if (! double.TryParse(args[2], out value)) { Output.Add(String.Format("The parameter value {0} is not a valid number.", args[2])); return Output; } SetSunParameter(args[1].ToLower(), value); Output.Add(String.Format("Parameter {0} set to {1}.", args[1], value.ToString())); } return Output; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Xna.Framework; namespace CocosSharp { public class CCTileMapAtlas : CCAtlasNode { #region Properties protected int NumOfItemsToRender { get; private set; } protected Dictionary<CCGridSize, int> PositionToAtlasIndex { get; private set; } internal CCImageTGA TGAInfo { get; private set; } #endregion Properties #region Constructors public CCTileMapAtlas(string tile, string mapFile, int tileWidth, int tileHeight) : this(tile, mapFile, tileWidth, tileHeight, new CCImageTGA(CCFileUtils.FullPathFromRelativePath(mapFile))) { } CCTileMapAtlas(string tile, string mapFile, int tileWidth, int tileHeight, CCImageTGA tgaInfo) : this(tile, tileWidth, tileHeight, tgaInfo, CalculateItemsToRender(tgaInfo)) { } CCTileMapAtlas(string tile, int tileWidth, int tileHeight, CCImageTGA tgaInfo, int numOfItemsToRender) : base(tile, tileWidth, tileHeight, numOfItemsToRender) { TGAInfo = tgaInfo; NumOfItemsToRender = numOfItemsToRender; PositionToAtlasIndex = new Dictionary<CCGridSize, int>(); UpdateAtlasValues(); ContentSize = new CCSize(TGAInfo.Width * ItemWidth, TGAInfo.Height * ItemHeight); } // Just used during construction static int CalculateItemsToRender(CCImageTGA tgaInfo) { Debug.Assert(tgaInfo != null, "tgaInfo must be non-nil"); int itemsToRender = 0; var data = tgaInfo.ImageData; for (int i = 0, count = tgaInfo.Width * tgaInfo.Height; i < count; i++) { if (data[i].R != 0) { ++itemsToRender; } } return itemsToRender; } #endregion Constructors #region Scene callbacks protected override void AddedToScene() { base.AddedToScene(); if (Scene != null && TGAInfo != null) { UpdateAtlasValues(); } } #endregion Scene callbacks public void ReleaseMap() { TGAInfo = null; PositionToAtlasIndex = null; } public CCColor4B TileAt(CCGridSize position) { Debug.Assert(TGAInfo != null, "tgaInfo must not be nil"); Debug.Assert(position.X < TGAInfo.Width, "Invalid position.x"); Debug.Assert(position.Y < TGAInfo.Height, "Invalid position.y"); return new CCColor4B(TGAInfo.ImageData[position.X + position.Y * TGAInfo.Width]); } public void SetTile(CCColor4B tile, CCGridSize position) { Debug.Assert(TGAInfo != null, "tgaInfo must not be nil"); Debug.Assert(PositionToAtlasIndex != null, "posToAtlasIndex must not be nil"); Debug.Assert(position.X < TGAInfo.Width, "Invalid position.x"); Debug.Assert(position.Y < TGAInfo.Height, "Invalid position.x"); Debug.Assert(tile.R != 0, "R component must be non 0"); Color value = TGAInfo.ImageData[position.X + position.Y * TGAInfo.Width]; if (value.R == 0) { CCLog.Log("CocosSharp: Value.r must be non 0."); } else { TGAInfo.ImageData[position.X + position.Y * TGAInfo.Width] = new Color(tile.R, tile.G, tile.B, tile.A); // XXX: this method consumes a lot of memory // XXX: a tree of something like that shall be implemented int num = PositionToAtlasIndex[position]; UpdateAtlasValueAt(position, tile.ToColor(), num); } } #region Updating atlas void UpdateAtlasValueAt(CCGridSize pos, Color value, int index) { UpdateAtlasValueAt(pos.X, pos.Y, value, index); } void UpdateAtlasValueAt(int x, int y, Color value, int index) { float row = (float)(value.R % ItemsPerRow); float col = (float)(value.R / ItemsPerRow); float textureWide = (TextureAtlas.Texture.PixelsWide); float textureHigh = (TextureAtlas.Texture.PixelsHigh); float itemWidthInPixels = ItemWidth; float itemHeightInPixels = ItemHeight; #if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL float left = (2 * row * itemWidthInPixels + 1) / (2 * textureWide); float right = left + (itemWidthInPixels * 2 - 2) / (2 * textureWide); float top = (2 * col * itemHeightInPixels + 1) / (2 * textureHigh); float bottom = top + (itemHeightInPixels * 2 - 2) / (2 * textureHigh); #else float left = (row * itemWidthInPixels) / textureWide; float right = left + itemWidthInPixels / textureWide; float top = (col * itemHeightInPixels) / textureHigh; float bottom = top + itemHeightInPixels / textureHigh; #endif CCV3F_C4B_T2F_Quad quad = new CCV3F_C4B_T2F_Quad(); quad.TopLeft.TexCoords.U = left; quad.TopLeft.TexCoords.V = top; quad.TopRight.TexCoords.U = right; quad.TopRight.TexCoords.V = top; quad.BottomLeft.TexCoords.U = left; quad.BottomLeft.TexCoords.V = bottom; quad.BottomRight.TexCoords.U = right; quad.BottomRight.TexCoords.V = bottom; quad.BottomLeft.Vertices.X = (x * ItemWidth); quad.BottomLeft.Vertices.Y = (y * ItemHeight); quad.BottomLeft.Vertices.Z = 0.0f; quad.BottomRight.Vertices.X = (x * ItemWidth + ItemWidth); quad.BottomRight.Vertices.Y = (y * ItemHeight); quad.BottomRight.Vertices.Z = 0.0f; quad.TopLeft.Vertices.X = (x * ItemWidth); quad.TopLeft.Vertices.Y = (y * ItemHeight + ItemHeight); quad.TopLeft.Vertices.Z = 0.0f; quad.TopRight.Vertices.X = (x * ItemWidth + ItemWidth); quad.TopRight.Vertices.Y = (y * ItemHeight + ItemHeight); quad.TopRight.Vertices.Z = 0.0f; var color = new CCColor4B(DisplayedColor.R, DisplayedColor.G, DisplayedColor.B, DisplayedOpacity); quad.TopRight.Colors = color; quad.TopLeft.Colors = color; quad.BottomRight.Colors = color; quad.BottomLeft.Colors = color; TextureAtlas.UpdateQuad(ref quad, index); } public override void UpdateAtlasValues() { if(PositionToAtlasIndex.Count > 0) return; Debug.Assert(TGAInfo != null, "tgaInfo must be non-nil"); int total = 0; for (int x = 0; x < TGAInfo.Width; x++) { for (int y = 0; y < TGAInfo.Height; y++) { if (total < NumOfItemsToRender) { Color value = TGAInfo.ImageData[x + y * TGAInfo.Width]; if (value.R != 0) { var pos = new CCGridSize(x, y); UpdateAtlasValueAt(x, y, value, total); PositionToAtlasIndex.Add(pos, total); total++; } } } } } #endregion Updating atlas } }
using System; using System.Linq; using System.Threading.Tasks; using AllReady.Areas.Admin.Features.Events; using AllReady.Areas.Admin.Features.Campaigns; using AllReady.Areas.Admin.Features.Requests; using AllReady.Extensions; using AllReady.Models; using AllReady.Security; using AllReady.Services; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using AllReady.Areas.Admin.ViewModels.Event; using AllReady.Areas.Admin.ViewModels.Validators; using AllReady.Areas.Admin.ViewModels.Request; using AllReady.Constants; using DeleteQuery = AllReady.Areas.Admin.Features.Events.DeleteQuery; namespace AllReady.Areas.Admin.Controllers { [Area(AreaNames.Admin)] [Authorize] public class EventController : Controller { public Func<DateTime> DateTimeTodayDate = () => DateTime.Today.Date; private readonly IImageService _imageService; private readonly IMediator _mediator; private readonly IValidateEventEditViewModels _eventEditViewModelValidator; private readonly IUserAuthorizationService _userAuthorizationService; private readonly IImageSizeValidator _imageSizeValidator; public EventController(IImageService imageService, IMediator mediator, IValidateEventEditViewModels eventEditViewModelValidator, IUserAuthorizationService userAuthorizationService, IImageSizeValidator imageSizeValidator) { _imageService = imageService; _mediator = mediator; _eventEditViewModelValidator = eventEditViewModelValidator; _userAuthorizationService = userAuthorizationService; _imageSizeValidator = imageSizeValidator; } [HttpGet] [Route("Admin/Event/ListAll")] public async Task<IActionResult> Lister() { var viewModel = await _mediator.SendAsync(new EventListerQuery {UserId = _userAuthorizationService.AssociatedUserId}); return View(viewModel); } [HttpGet] [Route("Admin/Event/Details/{id}")] public async Task<IActionResult> Details(int id) { var viewModel = await _mediator.SendAsync(new EventDetailQuery { EventId = id }); if (viewModel == null) { return NotFound(); } var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(viewModel.Id, viewModel.CampaignId, viewModel.OrganizationId)); if (!await authorizableEvent.UserCanView()) { return new ForbidResult(); } // todo - check if the user can duplicate (e.g. create events) against the campaign as well - depends on having an authorizable campaign class first if (await authorizableEvent.UserCanDelete()) { viewModel.ShowDeleteButton = true; } if (await authorizableEvent.UserCanManageChildObjects()) { viewModel.ShowCreateChildObjectButtons = true; } return View(viewModel); } [HttpGet] [Route("Admin/Event/Create/{campaignId}")] public async Task<IActionResult> Create(int campaignId) { var campaign = await _mediator.SendAsync(new CampaignSummaryQuery { CampaignId = campaignId }); var authorizableCampaign = await _mediator.SendAsync(new AuthorizableCampaignQuery(campaign.Id, campaign.OrganizationId)); if (!await authorizableCampaign.UserCanManageChildObjects()) { return new ForbidResult(); } var viewModel = new EventEditViewModel { CampaignId = campaign.Id, CampaignName = campaign.Name, TimeZoneId = campaign.TimeZoneId, OrganizationId = campaign.OrganizationId, OrganizationName = campaign.OrganizationName, StartDateTime = DateTimeTodayDate(), EndDateTime = DateTimeTodayDate(), CampaignStartDateTime = campaign.StartDate, CampaignEndDateTime = campaign.EndDate }; return View("Edit", viewModel); } [HttpPost] [ValidateAntiForgeryToken] [Route("Admin/Event/Create/{campaignId}")] public async Task<IActionResult> Create(int campaignId, EventEditViewModel eventEditViewModel, IFormFile fileUpload) { var campaign = await _mediator.SendAsync(new CampaignSummaryQuery { CampaignId = campaignId }); var authorizableCampaign = await _mediator.SendAsync(new AuthorizableCampaignQuery(campaign.Id, campaign.OrganizationId)); if (!await authorizableCampaign.UserCanManageChildObjects()) { return new ForbidResult(); } var errors = _eventEditViewModelValidator.Validate(eventEditViewModel, campaign); errors.ToList().ForEach(e => ModelState.AddModelError(e.Key, e.Value)); ModelState.Remove("NewItinerary"); //TryValidateModel is called explictly because of MVC 6 behavior that supresses model state validation during model binding when binding to an IFormFile. //See #619. if (ModelState.IsValid && TryValidateModel(eventEditViewModel)) { if (fileUpload != null) { if (!fileUpload.IsAcceptableImageContentType()) { ModelState.AddModelError(nameof(eventEditViewModel.ImageUrl), "You must upload a valid image file for the logo (.jpg, .png, .gif)"); return View("Edit", eventEditViewModel); } if (_imageSizeValidator != null && fileUpload.Length > _imageSizeValidator.FileSizeInBytes) { ModelState.AddModelError(nameof(eventEditViewModel.ImageUrl), $"File size must be less than {_imageSizeValidator.BytesToMb():#,##0.00}MB!"); return View("Edit", eventEditViewModel); } } eventEditViewModel.OrganizationId = campaign.OrganizationId; var id = await _mediator.SendAsync(new EditEventCommand { Event = eventEditViewModel }); if (fileUpload != null) { // resave now that event has the ImageUrl eventEditViewModel.Id = id; eventEditViewModel.ImageUrl = await _imageService.UploadEventImageAsync(campaign.OrganizationId, id, fileUpload); await _mediator.SendAsync(new EditEventCommand { Event = eventEditViewModel }); } return RedirectToAction(nameof(Details), new { area = AreaNames.Admin, id = id }); } return View("Edit", eventEditViewModel); } [HttpGet] public async Task<IActionResult> Edit(int id) { var campaignEvent = await _mediator.SendAsync(new EventEditQuery { EventId = id }); if (campaignEvent == null) { return NotFound(); } var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(id, campaignEvent.CampaignId, campaignEvent.OrganizationId)); if (!await authorizableEvent.UserCanEdit()) { return new ForbidResult(); } return View(campaignEvent); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(EventEditViewModel eventEditViewModel, IFormFile fileUpload) { if (eventEditViewModel == null) { return BadRequest(); } var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(eventEditViewModel.Id)); if (!await authorizableEvent.UserCanEdit()) { return new ForbidResult(); } var campaign = await _mediator.SendAsync(new CampaignSummaryQuery { CampaignId = eventEditViewModel.CampaignId }); var errors = _eventEditViewModelValidator.Validate(eventEditViewModel, campaign); errors.ForEach(e => ModelState.AddModelError(e.Key, e.Value)); if (ModelState.IsValid) { if (fileUpload != null) { if (!fileUpload.IsAcceptableImageContentType()) { ModelState.AddModelError(nameof(eventEditViewModel.ImageUrl), "You must upload a valid image file for the logo (.jpg, .png, .gif)"); return View(eventEditViewModel); } if (_imageSizeValidator != null && fileUpload.Length > _imageSizeValidator.FileSizeInBytes) { ModelState.AddModelError(nameof(eventEditViewModel.ImageUrl), $"File size must be less than {_imageSizeValidator.BytesToMb():#,##0.00}MB!"); return View("Edit", eventEditViewModel); } var existingImageUrl = eventEditViewModel.ImageUrl; var newImageUrl = await _imageService.UploadEventImageAsync(campaign.OrganizationId, eventEditViewModel.Id, fileUpload); if (!string.IsNullOrEmpty(newImageUrl)) { eventEditViewModel.ImageUrl = newImageUrl; if (existingImageUrl != null && existingImageUrl != newImageUrl) { await _imageService.DeleteImageAsync(existingImageUrl); } } } var id = await _mediator.SendAsync(new EditEventCommand { Event = eventEditViewModel }); return RedirectToAction(nameof(Details), new { area = AreaNames.Admin, id = id }); } return View(eventEditViewModel); } // GET: Event/Duplicate/5 [HttpGet] public async Task<IActionResult> Duplicate(int id) { var viewModel = await _mediator.SendAsync(new DuplicateEventQuery { EventId = id }); if (viewModel == null) { return NotFound(); } if (!User.IsOrganizationAdmin(viewModel.OrganizationId)) { return Unauthorized(); } viewModel.UserIsOrgAdmin = true; return View(viewModel); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Duplicate(DuplicateEventViewModel viewModel) { if (viewModel == null) { return BadRequest(); } if (!viewModel.UserIsOrgAdmin) { return Unauthorized(); } var existingEvent = await _mediator.SendAsync(new EventEditQuery { EventId = viewModel.Id }); var campaign = await _mediator.SendAsync(new CampaignSummaryQuery { CampaignId = existingEvent.CampaignId }); var newEvent = BuildNewEventDetailsModel(existingEvent, viewModel); //mgmccarthy: why are we validating here? We don't need to validate as the event that is being duplicated was already validated before it was created var errors = _eventEditViewModelValidator.Validate(newEvent, campaign); errors.ForEach(e => ModelState.AddModelError(e.Key, e.Value)); if (ModelState.IsValid) { var id = await _mediator.SendAsync(new DuplicateEventCommand { DuplicateEventModel = viewModel }); return RedirectToAction(nameof(Details), new { area = AreaNames.Admin, id }); } return View(viewModel); } [HttpGet] public async Task<IActionResult> Delete(int id) { var viewModel = await _mediator.SendAsync(new DeleteQuery { EventId = id }); if (viewModel == null) { return NotFound(); } var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(viewModel.Id, viewModel.CampaignId, viewModel.OrganizationId)); if (!await authorizableEvent.UserCanDelete()) { return new ForbidResult(); } ViewData["Title"] = $"Delete event {viewModel.Name}"; return View(viewModel); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(id)); if (!await authorizableEvent.UserCanDelete()) { return new ForbidResult(); } await _mediator.SendAsync(new DeleteEventCommand { EventId = id }); return RedirectToAction(nameof(CampaignController.Details), "Campaign", new { area = AreaNames.Admin, id = authorizableEvent.CampaignId }); } [HttpPost] [ValidateAntiForgeryToken] public async Task<JsonResult> DeleteEventImage(int eventId) { var campaignEvent = await _mediator.SendAsync(new EventEditQuery { EventId = eventId }); if (campaignEvent == null) { return Json(new { status = "NotFound" }); } var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(campaignEvent.Id, campaignEvent.CampaignId, campaignEvent.OrganizationId)); if (!await authorizableEvent.UserCanEdit()) { return Json(new { status = "Unauthorized" }); } if (campaignEvent.ImageUrl != null) { await _imageService.DeleteImageAsync(campaignEvent.ImageUrl); campaignEvent.ImageUrl = null; await _mediator.SendAsync(new EditEventCommand { Event = campaignEvent }); return Json(new { status = "Success" }); } return Json(new { status = "NothingToDelete" }); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> MessageAllVolunteers(MessageEventVolunteersViewModel viewModel) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(viewModel.EventId)); if (!await authorizableEvent.UserCanEdit()) { return new ForbidResult(); } await _mediator.SendAsync(new MessageEventVolunteersCommand { ViewModel = viewModel }); return Ok(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> PostEventFile(int id, IFormFile file) { var organizationId = await _mediator.SendAsync(new OrganizationIdByEventIdQuery { EventId = id }); var imageUrl = await _imageService.UploadEventImageAsync(organizationId, id, file); await _mediator.SendAsync(new UpdateEventImageUrl { EventId = id, ImageUrl = imageUrl }); return RedirectToRoute(new { controller = "Event", area = AreaNames.Admin, action = nameof(Edit), id }); } [HttpGet] [Route("Admin/Event/[action]/{id}/{status?}")] public async Task<IActionResult> Requests(int id, string status) { var authorizableEvent = await _mediator.SendAsync(new AuthorizableEventQuery(id)); if (!await authorizableEvent.UserCanView()) { return new ForbidResult(); } var criteria = new RequestSearchCriteria { EventId = id }; var pageTitle = "All Requests"; var currentPage = "All"; if (!string.IsNullOrEmpty(status)) { RequestStatus requestStatus; if (Enum.TryParse(status, out requestStatus)) { criteria.Status = requestStatus; pageTitle = $"{status} Requests"; currentPage = status; } else { return RedirectToAction(nameof(Requests), new { id }); } } var viewModel = await _mediator.SendAsync(new EventRequestsQuery { EventId = id }); viewModel.PageTitle = pageTitle; viewModel.CurrentPage = currentPage; viewModel.Requests = await _mediator.SendAsync(new RequestListItemsQuery { Criteria = criteria }); return View(viewModel); } private static EventEditViewModel BuildNewEventDetailsModel(EventEditViewModel existingEvent, DuplicateEventViewModel newEventDetails) { existingEvent.Id = 0; existingEvent.Name = newEventDetails.Name; existingEvent.Description = newEventDetails.Description; existingEvent.StartDateTime = newEventDetails.StartDateTime; existingEvent.EndDateTime = newEventDetails.EndDateTime; return existingEvent; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Diagnostics; using System.ComponentModel; namespace System.DirectoryServices.ActiveDirectory { public enum NotificationStatus { NoNotification = 0, IntraSiteOnly = 1, NotificationAlways = 2 } public enum ReplicationSpan { IntraSite = 0, InterSite = 1 } public class ReplicationConnection : IDisposable { internal readonly DirectoryContext context = null; internal readonly DirectoryEntry cachedDirectoryEntry = null; internal bool existingConnection = false; private bool _disposed = false; private readonly bool _checkADAM = false; private bool _isADAMServer = false; private int _options = 0; private readonly string _connectionName = null; private string _sourceServerName = null; private string _destinationServerName = null; private readonly ActiveDirectoryTransportType _transport = ActiveDirectoryTransportType.Rpc; private const string ADAMGuid = "1.2.840.113556.1.4.1851"; public static ReplicationConnection FindByName(DirectoryContext context, string name) { ValidateArgument(context, name); // work with copy of the context context = new DirectoryContext(context); // bind to the rootdse to get the servername property DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { string serverDN = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ServerName); string connectionContainer = "CN=NTDS Settings," + serverDN; de = DirectoryEntryManager.GetDirectoryEntry(context, connectionContainer); // doing the search to find the connection object based on its name ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=nTDSConnection)(objectCategory=NTDSConnection)(name=" + Utils.GetEscapedFilterValue(name) + "))", new string[] { "distinguishedName" }, SearchScope.OneLevel, false, /* no paged search */ false /* don't cache results */); SearchResult srchResult = null; try { srchResult = adSearcher.FindOne(); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ReplicationConnection), name); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } if (srchResult == null) { // no such connection object Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ReplicationConnection), name); throw e; } else { DirectoryEntry connectionEntry = srchResult.GetDirectoryEntry(); return new ReplicationConnection(context, connectionEntry, name); } } finally { de.Dispose(); } } internal ReplicationConnection(DirectoryContext context, DirectoryEntry connectionEntry, string name) { this.context = context; cachedDirectoryEntry = connectionEntry; _connectionName = name; // this is an exising connection object existingConnection = true; } public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer) : this(context, name, sourceServer, null, ActiveDirectoryTransportType.Rpc) { } public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer, ActiveDirectorySchedule schedule) : this(context, name, sourceServer, schedule, ActiveDirectoryTransportType.Rpc) { } public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer, ActiveDirectoryTransportType transport) : this(context, name, sourceServer, null, transport) { } public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer, ActiveDirectorySchedule schedule, ActiveDirectoryTransportType transport) { ValidateArgument(context, name); if (sourceServer == null) throw new ArgumentNullException(nameof(sourceServer)); if (transport < ActiveDirectoryTransportType.Rpc || transport > ActiveDirectoryTransportType.Smtp) throw new InvalidEnumArgumentException("value", (int)transport, typeof(ActiveDirectoryTransportType)); // work with copy of the context context = new DirectoryContext(context); ValidateTargetAndSourceServer(context, sourceServer); this.context = context; _connectionName = name; _transport = transport; DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { string serverDN = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ServerName); string connectionContainer = "CN=NTDS Settings," + serverDN; de = DirectoryEntryManager.GetDirectoryEntry(context, connectionContainer); // create the connection entry string rdn = "cn=" + _connectionName; rdn = Utils.GetEscapedPath(rdn); cachedDirectoryEntry = de.Children.Add(rdn, "nTDSConnection"); // set all the properties // sourceserver property DirectoryContext sourceServerContext = sourceServer.Context; de = DirectoryEntryManager.GetDirectoryEntry(sourceServerContext, WellKnownDN.RootDSE); string serverName = (string)PropertyManager.GetPropertyValue(sourceServerContext, de, PropertyManager.ServerName); serverName = "CN=NTDS Settings," + serverName; cachedDirectoryEntry.Properties["fromServer"].Add(serverName); // schedule property if (schedule != null) cachedDirectoryEntry.Properties[nameof(schedule)].Value = schedule.GetUnmanagedSchedule(); // transporttype property string transportPath = Utils.GetDNFromTransportType(TransportType, context); // verify that the transport is supported de = DirectoryEntryManager.GetDirectoryEntry(context, transportPath); try { de.Bind(true); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { // if it is ADAM and transport type is SMTP, throw NotSupportedException. DirectoryEntry tmpDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); if (Utils.CheckCapability(tmpDE, Capability.ActiveDirectoryApplicationMode) && transport == ActiveDirectoryTransportType.Smtp) { throw new NotSupportedException(SR.NotSupportTransportSMTP); } } throw ExceptionHelper.GetExceptionFromCOMException(context, e); } cachedDirectoryEntry.Properties["transportType"].Add(transportPath); // enabledConnection property cachedDirectoryEntry.Properties["enabledConnection"].Value = false; // options cachedDirectoryEntry.Properties["options"].Value = 0; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { de.Close(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing && cachedDirectoryEntry != null) cachedDirectoryEntry.Dispose(); _disposed = true; } } ~ReplicationConnection() { Dispose(false); // finalizer is called => Dispose has not been called yet. } public string Name { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); return _connectionName; } } public string SourceServer { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); // get the source server if (_sourceServerName == null) { string sourceServerDN = (string)PropertyManager.GetPropertyValue(context, cachedDirectoryEntry, PropertyManager.FromServer); DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, sourceServerDN); if (IsADAM) { int portnumber = (int)PropertyManager.GetPropertyValue(context, de, PropertyManager.MsDSPortLDAP); string tmpServerName = (string)PropertyManager.GetPropertyValue(context, de.Parent, PropertyManager.DnsHostName); if (portnumber != 389) { _sourceServerName = tmpServerName + ":" + portnumber; } } else { _sourceServerName = (string)PropertyManager.GetPropertyValue(context, de.Parent, PropertyManager.DnsHostName); } } return _sourceServerName; } } public string DestinationServer { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (_destinationServerName == null) { DirectoryEntry NTDSObject = null; DirectoryEntry serverObject = null; try { NTDSObject = cachedDirectoryEntry.Parent; serverObject = NTDSObject.Parent; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } string hostName = (string)PropertyManager.GetPropertyValue(context, serverObject, PropertyManager.DnsHostName); if (IsADAM) { int portnumber = (int)PropertyManager.GetPropertyValue(context, NTDSObject, PropertyManager.MsDSPortLDAP); if (portnumber != 389) { _destinationServerName = hostName + ":" + portnumber; } else _destinationServerName = hostName; } else _destinationServerName = hostName; } return _destinationServerName; } } public bool Enabled { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); // fetch the property value try { if (cachedDirectoryEntry.Properties.Contains("enabledConnection")) return (bool)cachedDirectoryEntry.Properties["enabledConnection"][0]; else return false; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { cachedDirectoryEntry.Properties["enabledConnection"].Value = value; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public ActiveDirectoryTransportType TransportType { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); // for exisint connection, we need to check its property, for newly created and not committed one, we just return // the member variable value directly if (existingConnection) { PropertyValueCollection propValue = null; try { propValue = cachedDirectoryEntry.Properties["transportType"]; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (propValue.Count == 0) { // if the property does not exist, then default is to RPC over IP return ActiveDirectoryTransportType.Rpc; } else { return Utils.GetTransportTypeFromDN((string)propValue[0]); } } else return _transport; } } public bool GeneratedByKcc { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); PropertyValueCollection propValue = null; try { propValue = cachedDirectoryEntry.Properties["options"]; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (propValue.Count == 0) { _options = 0; } else { _options = (int)propValue[0]; } // NTDSCONN_OPT_IS_GENERATED ( 1 << 0 ) object generated by DS, not admin if ((_options & 0x1) == 0) return false; else return true; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"]; if (propValue.Count == 0) { _options = 0; } else { _options = (int)propValue[0]; } // NTDSCONN_OPT_IS_GENERATED ( 1 << 0 ) object generated by DS, not admin if (value) { _options |= 0x1; } else { _options &= (~(0x1)); } // put the value into cache cachedDirectoryEntry.Properties["options"].Value = _options; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public bool ReciprocalReplicationEnabled { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); PropertyValueCollection propValue = null; try { propValue = cachedDirectoryEntry.Properties["options"]; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (propValue.Count == 0) { // if the property does not exist, then default is to RPC over IP _options = 0; } else { _options = (int)propValue[0]; } // NTDSCONN_OPT_TWOWAY_SYNC ( 1 << 1 ) force sync in opposite direction at end of sync if ((_options & 0x2) == 0) return false; else return true; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"]; if (propValue.Count == 0) { _options = 0; } else { _options = (int)propValue[0]; } // NTDSCONN_OPT_TWOWAY_SYNC ( 1 << 1 ) force sync in opposite direction at end of sync if (value == true) { _options |= 0x2; } else { _options &= (~(0x2)); } // put the value into cache cachedDirectoryEntry.Properties["options"].Value = _options; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public NotificationStatus ChangeNotificationStatus { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); PropertyValueCollection propValue = null; try { propValue = cachedDirectoryEntry.Properties["options"]; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (propValue.Count == 0) { // if the property does not exist, then default is to RPC over IP _options = 0; } else { _options = (int)propValue[0]; } int overrideNotify = _options & 0x4; int userNotify = _options & 0x8; if (overrideNotify == 0x4 && userNotify == 0) return NotificationStatus.NoNotification; else if (overrideNotify == 0x4 && userNotify == 0x8) return NotificationStatus.NotificationAlways; else return NotificationStatus.IntraSiteOnly; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (value < NotificationStatus.NoNotification || value > NotificationStatus.NotificationAlways) throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(NotificationStatus)); try { PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"]; if (propValue.Count == 0) { _options = 0; } else { _options = (int)propValue[0]; } if (value == NotificationStatus.IntraSiteOnly) { _options &= (~(0x4)); _options &= (~(0x8)); } else if (value == NotificationStatus.NoNotification) { _options |= (0x4); _options &= (~(0x8)); } else { _options |= (0x4); _options |= (0x8); } // put the value into cache cachedDirectoryEntry.Properties["options"].Value = _options; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public bool DataCompressionEnabled { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); PropertyValueCollection propValue = null; try { propValue = cachedDirectoryEntry.Properties["options"]; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (propValue.Count == 0) { // if the property does not exist, then default is to RPC over IP _options = 0; } else { _options = (int)propValue[0]; } //NTDSCONN_OPT_DISABLE_INTERSITE_COMPRESSION (1 << 4) // 0 - Compression of replication data enabled // 1 - Compression of replication data disabled if ((_options & 0x10) == 0) return true; else return false; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"]; if (propValue.Count == 0) { _options = 0; } else { _options = (int)propValue[0]; } //NTDSCONN_OPT_DISABLE_INTERSITE_COMPRESSION (1 << 4) // 0 - Compression of replication data enabled // 1 - Compression of replication data disabled if (value == false) { _options |= 0x10; } else { _options &= (~(0x10)); } // put the value into cache cachedDirectoryEntry.Properties["options"].Value = _options; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public bool ReplicationScheduleOwnedByUser { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); PropertyValueCollection propValue = null; try { propValue = cachedDirectoryEntry.Properties["options"]; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (propValue.Count == 0) { // if the property does not exist, then default is to RPC over IP _options = 0; } else { _options = (int)propValue[0]; } // NTDSCONN_OPT_USER_OWNED_SCHEDULE (1 << 5) if ((_options & 0x20) == 0) return false; else return true; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"]; if (propValue.Count == 0) { _options = 0; } else { _options = (int)propValue[0]; } // NTDSCONN_OPT_USER_OWNED_SCHEDULE (1 << 5) if (value == true) { _options |= 0x20; } else { _options &= (~(0x20)); } // put the value into cache cachedDirectoryEntry.Properties["options"].Value = _options; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public ReplicationSpan ReplicationSpan { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); // find out whether the site and the destination is in the same site string destinationPath = (string)PropertyManager.GetPropertyValue(context, cachedDirectoryEntry, PropertyManager.FromServer); string destinationSite = Utils.GetDNComponents(destinationPath)[3].Value; DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string serverDN = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ServerName); string serverSite = Utils.GetDNComponents(serverDN)[2].Value; if (Utils.Compare(destinationSite, serverSite) == 0) { return ReplicationSpan.IntraSite; } else { return ReplicationSpan.InterSite; } } } public ActiveDirectorySchedule ReplicationSchedule { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); ActiveDirectorySchedule schedule = null; bool scheduleExists = false; try { scheduleExists = cachedDirectoryEntry.Properties.Contains("schedule"); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (scheduleExists) { byte[] tmpSchedule = (byte[])cachedDirectoryEntry.Properties["schedule"][0]; Debug.Assert(tmpSchedule != null && tmpSchedule.Length == 188); schedule = new ActiveDirectorySchedule(); schedule.SetUnmanagedSchedule(tmpSchedule); } return schedule; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { if (value == null) { if (cachedDirectoryEntry.Properties.Contains("schedule")) cachedDirectoryEntry.Properties["schedule"].Clear(); } else { cachedDirectoryEntry.Properties["schedule"].Value = value.GetUnmanagedSchedule(); } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } private bool IsADAM { get { if (!_checkADAM) { DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); PropertyValueCollection values = null; try { values = de.Properties["supportedCapabilities"]; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (values.Contains(ADAMGuid)) _isADAMServer = true; } return _isADAMServer; } } public void Delete() { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (!existingConnection) { throw new InvalidOperationException(SR.CannotDelete); } else { try { cachedDirectoryEntry.Parent.Children.Remove(cachedDirectoryEntry); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public void Save() { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { cachedDirectoryEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (!existingConnection) { existingConnection = true; } } public override string ToString() { if (_disposed) throw new ObjectDisposedException(GetType().Name); return Name; } public DirectoryEntry GetDirectoryEntry() { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (!existingConnection) { throw new InvalidOperationException(SR.CannotGetObject); } else { return DirectoryEntryManager.GetDirectoryEntryInternal(context, cachedDirectoryEntry.Path); } } private static void ValidateArgument(DirectoryContext context, string name) { if (context == null) throw new ArgumentNullException(nameof(context)); // the target of the scope must be server if (context.Name == null || !context.isServer()) throw new ArgumentException(SR.DirectoryContextNeedHost); if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, nameof(name)); } private void ValidateTargetAndSourceServer(DirectoryContext context, DirectoryServer sourceServer) { bool targetIsDC = false; DirectoryEntry targetDE = null; DirectoryEntry sourceDE = null; // first find out target is a dc or ADAM instance targetDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { if (Utils.CheckCapability(targetDE, Capability.ActiveDirectory)) { targetIsDC = true; } else if (!Utils.CheckCapability(targetDE, Capability.ActiveDirectoryApplicationMode)) { // if it is also not an ADAM instance, it is invalid then throw new ArgumentException(SR.DirectoryContextNeedHost, nameof(context)); } if (targetIsDC && !(sourceServer is DomainController)) { // target and sourceServer are not of the same type throw new ArgumentException(SR.ConnectionSourcServerShouldBeDC, nameof(sourceServer)); } else if (!targetIsDC && (sourceServer is DomainController)) { // target and sourceServer are not of the same type throw new ArgumentException(SR.ConnectionSourcServerShouldBeADAM, nameof(sourceServer)); } sourceDE = DirectoryEntryManager.GetDirectoryEntry(sourceServer.Context, WellKnownDN.RootDSE); // now if they are both dc, we need to check whether they come from the same forest if (targetIsDC) { string targetRoot = (string)PropertyManager.GetPropertyValue(context, targetDE, PropertyManager.RootDomainNamingContext); string sourceRoot = (string)PropertyManager.GetPropertyValue(sourceServer.Context, sourceDE, PropertyManager.RootDomainNamingContext); if (Utils.Compare(targetRoot, sourceRoot) != 0) { throw new ArgumentException(SR.ConnectionSourcServerSameForest, nameof(sourceServer)); } } else { string targetRoot = (string)PropertyManager.GetPropertyValue(context, targetDE, PropertyManager.ConfigurationNamingContext); string sourceRoot = (string)PropertyManager.GetPropertyValue(sourceServer.Context, sourceDE, PropertyManager.ConfigurationNamingContext); if (Utils.Compare(targetRoot, sourceRoot) != 0) { throw new ArgumentException(SR.ConnectionSourcServerSameConfigSet, nameof(sourceServer)); } } } catch (COMException e) { ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { if (targetDE != null) targetDE.Close(); if (sourceDE != null) sourceDE.Close(); } } } }
// 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.Collections.ObjectModel; using System.Linq; using Xunit; namespace System.Collections.Tests { public class QueueTests { [Fact] public void Ctors() { // Construct queues using the various constructors and make sure the count is correct Assert.Equal(0, new Queue<int>().Count); Assert.Equal(0, new Queue<int>(5).Count); Assert.Equal(0, new Queue<int>(Array.Empty<int>()).Count); Assert.Equal(5, new Queue<int>(Enumerable.Range(0, 5)).Count); // Make sure a queue constructed from an enumerated contains the right elements in the right order int count = 0; foreach (int i in new Queue<int>(Enumerable.Range(0, 5))) { Assert.Equal(count++, i); } // Verify arguments Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new Queue<int>(-1)); Assert.Throws<ArgumentNullException>("collection", () => new Queue<int>(null)); } [Theory] [MemberData("Collections")] public void Ctor_IEnumerable(IEnumerable<int> collection) { var q = new Queue<int>(collection); Assert.Equal(collection, q); foreach (int item in collection) { Assert.Equal(item, q.Dequeue()); } Assert.Equal(0, q.Count); } [Theory] [MemberData("Collections")] public void Ctor_IEnumerable_EnqueueDequeue(IEnumerable<int> collection) { var q = new Queue<int>(collection); q.Enqueue(int.MaxValue); q.Enqueue(int.MinValue); foreach (int item in collection) { Assert.Equal(item, q.Dequeue()); } Assert.Equal(int.MaxValue, q.Dequeue()); Assert.Equal(int.MinValue, q.Dequeue()); Assert.Equal(0, q.Count); } [Theory] [MemberData("NonEmptyCollections")] public void Ctor_IEnumerable_Dequeue(IEnumerable<int> collection) { var q = new Queue<int>(collection); IEnumerator<int> e = collection.GetEnumerator(); Assert.True(e.MoveNext()); Assert.Equal(e.Current, q.Dequeue()); while (e.MoveNext()) { Assert.Equal(e.Current, q.Dequeue()); } Assert.Equal(0, q.Count); } [Theory] [MemberData("NonEmptyCollections")] public void Ctor_IEnumerable_DequeueEnqueue(IEnumerable<int> collection) { var q = new Queue<int>(collection); IEnumerator<int> e = collection.GetEnumerator(); Assert.True(e.MoveNext()); Assert.Equal(e.Current, q.Dequeue()); q.Enqueue(int.MaxValue); while (e.MoveNext()) { Assert.Equal(e.Current, q.Dequeue()); } Assert.Equal(int.MaxValue, q.Dequeue()); Assert.Equal(0, q.Count); } public static IEnumerable<object[]> Collections { get { return GenerateCollections(includeEmptyCollections: true); } } public static IEnumerable<object[]> NonEmptyCollections { get { return GenerateCollections(includeEmptyCollections: false); } } private static IEnumerable<object[]> GenerateCollections(bool includeEmptyCollections) { var sizes = new List<int> { 65, 64, 5, 4, 3, 2, 1 }; if (includeEmptyCollections) sizes.Add(0); foreach (int size in sizes) { yield return new object[] { Enumerable.Range(0, size).ToArray() }; yield return new object[] { Enumerable.Range(0, size).ToList() }; yield return new object[] { new Collection<int>(Enumerable.Range(0, size).ToList()) }; yield return new object[] { new ReadOnlyCollection<int>(Enumerable.Range(0, size).ToList()) }; yield return new object[] { CreateIteratorCollection(size) }; } } private static IEnumerable<int> CreateIteratorCollection(int size) { for (int i = 0; i < size; i++) { yield return i; } } [Theory] [InlineData(0, 5)] [InlineData(1, 1)] [InlineData(3, 100)] public void EnqueueAndDequeue(int capacity, int items) { var q = new Queue<int>(capacity); Assert.Equal(0, q.Count); // Enqueue some values and make sure the count is correct for (int i = 0; i < items; i++) { q.Enqueue(i); } Assert.Equal(items, q.Count); // Iterate to make sure the values are all there in the right order int count = 0; foreach (int i in q) { Assert.Equal(count++, i); } // Dequeue to make sure the values are removed in the right order and the count is updated count = 0; for (int i = 0; i < items; i++) { Assert.Equal(count++, q.Dequeue()); Assert.Equal(items - i - 1, q.Count); } // Can't dequeue when empty Assert.Throws<InvalidOperationException>(() => q.Dequeue()); // But can still be used after a failure and after bouncing at empty q.Enqueue(42); Assert.Equal(42, q.Dequeue()); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] public void Clear_Empty(int capacity) { var q = new Queue<int>(capacity); Assert.Equal(0, q.Count); q.Clear(); Assert.Equal(0, q.Count); } [Fact] public void Clear_Normal() { var q = new Queue<string>(); Assert.Equal(0, q.Count); for (int repeat = 0; repeat < 2; repeat++) // repeat to ensure we can grow after emptying { // Add some elements for (int i = 0; i < 5; i++) { q.Enqueue(i.ToString()); } Assert.Equal(5, q.Count); Assert.True(q.GetEnumerator().MoveNext()); // Clear them and make sure they're gone q.Clear(); Assert.Equal(0, q.Count); Assert.False(q.GetEnumerator().MoveNext()); } } [Theory] [InlineData(true)] [InlineData(false)] public void Clear_Wrapped(bool initializeFromCollection) { // Try to exercise special case of clearing when we've wrapped around Queue<string> q = CreateQueueAtCapacity(initializeFromCollection, i => i.ToString(), size: 4); Assert.Equal("0", q.Dequeue()); Assert.Equal("1", q.Dequeue()); q.Enqueue("5"); q.Enqueue("6"); Assert.Equal(4, q.Count); q.Clear(); Assert.Equal(0, q.Count); Assert.False(q.GetEnumerator().MoveNext()); } [Fact] public void Peek() { var q = new Queue<int>(); Assert.Throws<InvalidOperationException>(() => q.Peek()); q.Enqueue(1); Assert.Equal(1, q.Peek()); q.Enqueue(2); Assert.Equal(1, q.Peek()); Assert.Equal(1, q.Dequeue()); Assert.Equal(2, q.Peek()); Assert.Equal(2, q.Dequeue()); } [Fact] public void Contains_ValueType() { var q = new Queue<int>(); // Add some elements for (int i = 0; i < 10; i++) { if (i % 2 == 0) { q.Enqueue(i); } } // Look them up using contains, making sure those and only those that should be there are there for (int i = 0; i < 10; i++) { Assert.Equal(i % 2 == 0, q.Contains(i)); } } [Fact] public void Contains_ReferenceType() { var q = new Queue<string>(); // Add some elements for (int i = 0; i < 10; i++) { if (i % 2 == 0) { q.Enqueue(i.ToString()); } else { q.Enqueue(null); } } // Look them up using contains, making sure those and only those that should be there are there for (int i = 0; i < 10; i++) { Assert.Equal(i % 2 == 0, q.Contains(i.ToString())); } // Make sure we can find a null value we enqueued Assert.True(q.Contains(null)); } [Fact] public void CopyTo_Normal() { var q = new Queue<int>(); // Copy an empty queue var arr = new int[0]; q.CopyTo(arr, 0); // Fill the queue q = new Queue<int>(Enumerable.Range(0, 10)); arr = new int[q.Count]; // Copy the queue's elements to an array q.CopyTo(arr, 0); for (int i = 0; i < 10; i++) { Assert.Equal(i, arr[i]); } // Dequeue some elements for (int i = 0; i < 3; i++) { Assert.Equal(i, q.Dequeue()); } // Copy the remaining ones to a different location q.CopyTo(arr, 1); Assert.Equal(0, arr[0]); for (int i = 1; i < 8; i++) { Assert.Equal(i + 2, arr[i]); } for (int i = 8; i < 10; i++) { Assert.Equal(i, arr[i]); } } [Theory] [InlineData(true)] [InlineData(false)] public void CopyTo_Wrapped(bool initializeFromCollection) { // Create a queue whose head has wrapped around Queue<int> q = CreateQueueAtCapacity(initializeFromCollection, i => i, size: 4); Assert.Equal(0, q.Dequeue()); Assert.Equal(1, q.Dequeue()); Assert.Equal(2, q.Count); q.Enqueue(4); q.Enqueue(5); Assert.Equal(4, q.Count); // Now copy; should require two copies under the covers int[] arr = new int[4]; q.CopyTo(arr, 0); for (int i = 0; i < 4; i++) { Assert.Equal(i + 2, arr[i]); } } [Fact] public void CopyTo_ArgumentValidation() { // Argument validation var q = new Queue<int>(Enumerable.Range(0, 4)); Assert.Throws<ArgumentNullException>("array", () => q.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>("arrayIndex", () => q.CopyTo(new int[4], -1)); Assert.Throws<ArgumentOutOfRangeException>("arrayIndex", () => q.CopyTo(new int[4], 5)); Assert.Throws<ArgumentException>(() => q.CopyTo(new int[4], 1)); } [Theory] [InlineData(0, 0)] [InlineData(0, 10)] [InlineData(1, 10)] [InlineData(10, 10)] [InlineData(10, 100)] [InlineData(90, 100)] [InlineData(100, 100)] public void TrimExcess(int items, int capacity) { var q = new Queue<int>(capacity); for (int i = 0; i < items; i++) { q.Enqueue(i); } q.TrimExcess(); Assert.Equal(items, q.Count); Assert.Equal(Enumerable.Range(0, items), q); } [Fact] public void ICollection_IsSynchronized() { ICollection ic = new Queue<int>(); Assert.False(ic.IsSynchronized); } [Fact] public void ICollection_SyncRoot() { ICollection ic = new Queue<int>(); Assert.Same(ic.SyncRoot, ic.SyncRoot); Assert.NotNull(ic.SyncRoot); } [Fact] public void ICollection_Count() { ICollection ic = new Queue<int>(Enumerable.Range(0, 5)); Assert.Equal(5, ic.Count); } [Fact] public void ICollection_CopyTo_FastPath() { int[] arr = new int[1] { 1 }; ((ICollection)new Queue<int>(0)).CopyTo(arr, 0); Assert.Equal(1, arr[0]); } [Fact] public void ICollection_CopyTo_ArgumentExceptions() { ICollection ic = new Queue<int>(Enumerable.Range(0, 5)); Assert.Throws<ArgumentNullException>("array", () => ic.CopyTo(null, 0)); Assert.Throws<ArgumentException>(() => ic.CopyTo(new int[5, 5], 0)); Assert.Throws<ArgumentException>(() => ic.CopyTo(Array.CreateInstance(typeof(int), new[] { 10 }, new[] { 3 }), 0)); Assert.Throws<ArgumentOutOfRangeException>("index", () => ic.CopyTo(new int[10], -1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => ic.CopyTo(new int[10], 11)); Assert.Throws<ArgumentException>(() => ic.CopyTo(new int[10], 7)); Assert.Throws<ArgumentException>(() => ic.CopyTo(new string[10], 0)); } [Fact] public void ICollection_CopyTo_Normal() { var q = new Queue<int>(); var arr = new int[1] { 1 }; // Copy an empty queue ((ICollection)q).CopyTo(arr, 0); Assert.Equal(1, arr[0]); q = new Queue<int>(Enumerable.Range(0, 10)); arr = new int[q.Count]; // Copy the queue's elements to an array ((ICollection)q).CopyTo(arr, 0); for (int i = 0; i < 10; i++) { Assert.Equal(i, arr[i]); } // Dequeue some elements for (int i = 0; i < 3; i++) { Assert.Equal(i, q.Dequeue()); } // Copy the remaining ones to a different location ((ICollection)q).CopyTo(arr, 1); Assert.Equal(0, arr[0]); for (int i = 1; i < 8; i++) { Assert.Equal(i + 2, arr[i]); } for (int i = 8; i < 10; i++) { Assert.Equal(i, arr[i]); } } [Theory] [InlineData(true)] [InlineData(false)] public void ICollection_CopyTo_Wrapped(bool initializeFromCollection) { // Create a queue whose head has wrapped around Queue<int> q = CreateQueueAtCapacity(initializeFromCollection, i => i, size: 4); Assert.Equal(0, q.Dequeue()); Assert.Equal(1, q.Dequeue()); Assert.Equal(2, q.Count); q.Enqueue(4); q.Enqueue(5); Assert.Equal(4, q.Count); // Now copy; should require two copies under the covers int[] arr = new int[4]; ((ICollection)q).CopyTo(arr, 0); for (int i = 0; i < 4; i++) { Assert.Equal(i + 2, arr[i]); } } [Fact] public void IEnumerable() { var src = Enumerable.Range(10, 15); var q = new Queue<int>(src); // Get enumerators from the source and then for both IEnumerable and IEnumerable<T> for the queue IEnumerator<int> srcEnumerator = src.GetEnumerator(); IEnumerator nonGeneric = ((IEnumerable)q).GetEnumerator(); IEnumerator<int> generic = ((IEnumerable<int>)q).GetEnumerator(); // Current shouldn't yet be usable Assert.Throws<InvalidOperationException>(() => nonGeneric.Current); Assert.Throws<InvalidOperationException>(() => generic.Current); // Run through the sequences twice, the second time to help validate Reset for (int repeat = 0; repeat < 2; repeat++) { // Make sure every element in the source is in each of the queue's enumerators while (srcEnumerator.MoveNext()) { Assert.True(nonGeneric.MoveNext()); Assert.Equal(srcEnumerator.Current, nonGeneric.Current); Assert.True(generic.MoveNext()); Assert.Equal(srcEnumerator.Current, generic.Current); } // The queue's enumerators should now be done Assert.False(nonGeneric.MoveNext()); Assert.False(generic.MoveNext()); Assert.Throws<InvalidOperationException>(() => nonGeneric.Current); Assert.Throws<InvalidOperationException>(() => generic.Current); // Reset nonGeneric.Reset(); generic.Reset(); srcEnumerator = src.GetEnumerator(); // RangeIterator doesn't support reset } // Dispose the enumerators ((IDisposable)nonGeneric).Dispose(); generic.Dispose(); Assert.False(nonGeneric.MoveNext()); Assert.False(generic.MoveNext()); } [Fact] public void ToArray() { var q = new Queue<int>(4); // Verify behavior with an empty queue Assert.NotNull(q.ToArray()); Assert.Same(q.ToArray(), q.ToArray()); // Verify behavior with some elements for (int i = 0; i < 4; i++) { q.Enqueue(i); var arr = q.ToArray(); Assert.Equal(i + 1, arr.Length); for (int j = 0; j < arr.Length; j++) { Assert.Equal(j, arr[j]); } } // Verify behavior when we wrap around { Assert.Equal(0, q.Dequeue()); Assert.Equal(1, q.Dequeue()); q.Enqueue(4); q.Enqueue(5); var arr = q.ToArray(); for (int i = 0; i < arr.Length; i++) { Assert.Equal(i + 2, arr[i]); } } } private static Queue<T> CreateQueueAtCapacity<T>(bool initializeFromCollection, Func<int, T> selector, int size) { Queue<T> q; if (initializeFromCollection) { q = new Queue<T>(Enumerable.Range(0, size).Select(selector).ToArray()); } else { q = new Queue<T>(size); for (int i = 0; i < size; i++) { q.Enqueue(selector(i)); } } return q; } } }
// 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; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { public partial class Process : IDisposable { private bool _haveMainWindow; private IntPtr _mainWindowHandle; private string _mainWindowTitle; private bool _haveResponding; private bool _responding; private bool StartCore(ProcessStartInfo startInfo) { return startInfo.UseShellExecute ? StartWithShellExecuteEx(startInfo) : StartWithCreateProcess(startInfo); } private unsafe bool StartWithShellExecuteEx(ProcessStartInfo startInfo) { if (!string.IsNullOrEmpty(startInfo.UserName) || startInfo.Password != null) throw new InvalidOperationException(SR.CantStartAsUser); if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) throw new InvalidOperationException(SR.CantRedirectStreams); if (startInfo.StandardInputEncoding != null) throw new InvalidOperationException(SR.StandardInputEncodingNotAllowed); if (startInfo.StandardErrorEncoding != null) throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed); if (startInfo.StandardOutputEncoding != null) throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed); if (startInfo._environmentVariables != null) throw new InvalidOperationException(SR.CantUseEnvVars); string arguments; if (startInfo.ArgumentList.Count > 0) { StringBuilder sb = new StringBuilder(); Process.AppendArguments(sb, startInfo.ArgumentList); arguments = sb.ToString(); } else { arguments = startInfo.Arguments; } fixed (char* fileName = startInfo.FileName.Length > 0 ? startInfo.FileName : null) fixed (char* verb = startInfo.Verb.Length > 0 ? startInfo.Verb : null) fixed (char* parameters = arguments.Length > 0 ? arguments : null) fixed (char* directory = startInfo.WorkingDirectory.Length > 0 ? startInfo.WorkingDirectory : null) { Interop.Shell32.SHELLEXECUTEINFO shellExecuteInfo = new Interop.Shell32.SHELLEXECUTEINFO() { cbSize = (uint)sizeof(Interop.Shell32.SHELLEXECUTEINFO), lpFile = fileName, lpVerb = verb, lpParameters = parameters, lpDirectory = directory, fMask = Interop.Shell32.SEE_MASK_NOCLOSEPROCESS | Interop.Shell32.SEE_MASK_FLAG_DDEWAIT }; if (startInfo.ErrorDialog) shellExecuteInfo.hwnd = startInfo.ErrorDialogParentHandle; else shellExecuteInfo.fMask |= Interop.Shell32.SEE_MASK_FLAG_NO_UI; switch (startInfo.WindowStyle) { case ProcessWindowStyle.Hidden: shellExecuteInfo.nShow = Interop.Shell32.SW_HIDE; break; case ProcessWindowStyle.Minimized: shellExecuteInfo.nShow = Interop.Shell32.SW_SHOWMINIMIZED; break; case ProcessWindowStyle.Maximized: shellExecuteInfo.nShow = Interop.Shell32.SW_SHOWMAXIMIZED; break; default: shellExecuteInfo.nShow = Interop.Shell32.SW_SHOWNORMAL; break; } ShellExecuteHelper executeHelper = new ShellExecuteHelper(&shellExecuteInfo); if (!executeHelper.ShellExecuteOnSTAThread()) { int error = executeHelper.ErrorCode; if (error == 0) { error = GetShellError(shellExecuteInfo.hInstApp); } switch (error) { case Interop.Errors.ERROR_BAD_EXE_FORMAT: case Interop.Errors.ERROR_EXE_MACHINE_TYPE_MISMATCH: throw new Win32Exception(error, SR.InvalidApplication); case Interop.Errors.ERROR_CALL_NOT_IMPLEMENTED: // This happens on Windows Nano throw new PlatformNotSupportedException(SR.UseShellExecuteNotSupported); default: throw new Win32Exception(error); } } if (shellExecuteInfo.hProcess != IntPtr.Zero) { SetProcessHandle(new SafeProcessHandle(shellExecuteInfo.hProcess)); return true; } } return false; } private int GetShellError(IntPtr error) { switch ((long)error) { case Interop.Shell32.SE_ERR_FNF: return Interop.Errors.ERROR_FILE_NOT_FOUND; case Interop.Shell32.SE_ERR_PNF: return Interop.Errors.ERROR_PATH_NOT_FOUND; case Interop.Shell32.SE_ERR_ACCESSDENIED: return Interop.Errors.ERROR_ACCESS_DENIED; case Interop.Shell32.SE_ERR_OOM: return Interop.Errors.ERROR_NOT_ENOUGH_MEMORY; case Interop.Shell32.SE_ERR_DDEFAIL: case Interop.Shell32.SE_ERR_DDEBUSY: case Interop.Shell32.SE_ERR_DDETIMEOUT: return Interop.Errors.ERROR_DDE_FAIL; case Interop.Shell32.SE_ERR_SHARE: return Interop.Errors.ERROR_SHARING_VIOLATION; case Interop.Shell32.SE_ERR_NOASSOC: return Interop.Errors.ERROR_NO_ASSOCIATION; case Interop.Shell32.SE_ERR_DLLNOTFOUND: return Interop.Errors.ERROR_DLL_NOT_FOUND; default: return (int)(long)error; } } internal unsafe class ShellExecuteHelper { private Interop.Shell32.SHELLEXECUTEINFO* _executeInfo; private bool _succeeded; private bool _notpresent; public ShellExecuteHelper(Interop.Shell32.SHELLEXECUTEINFO* executeInfo) { _executeInfo = executeInfo; } private void ShellExecuteFunction() { try { if (!(_succeeded = Interop.Shell32.ShellExecuteExW(_executeInfo))) ErrorCode = Marshal.GetLastWin32Error(); } catch (EntryPointNotFoundException) { _notpresent = true; } } public bool ShellExecuteOnSTAThread() { // ShellExecute() requires STA in order to work correctly. if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) { ThreadStart threadStart = new ThreadStart(ShellExecuteFunction); Thread executionThread = new Thread(threadStart); executionThread.SetApartmentState(ApartmentState.STA); executionThread.Start(); executionThread.Join(); } else { ShellExecuteFunction(); } if (_notpresent) throw new PlatformNotSupportedException(SR.UseShellExecuteNotSupported); return _succeeded; } public int ErrorCode { get; private set; } } private string GetMainWindowTitle() { IntPtr handle = MainWindowHandle; if (handle == IntPtr.Zero) return string.Empty; int length = Interop.User32.GetWindowTextLengthW(handle); if (length == 0) { #if DEBUG // We never used to throw here, want to surface possible mistakes on our part int error = Marshal.GetLastWin32Error(); Debug.Assert(error == 0, $"Failed GetWindowTextLengthW(): { new Win32Exception(error).Message }"); #endif return string.Empty; } length++; // for null terminator, which GetWindowTextLengthW does not include in the length Span<char> title = length <= 256 ? stackalloc char[256] : new char[length]; unsafe { fixed (char* titlePtr = title) { length = Interop.User32.GetWindowTextW(handle, titlePtr, title.Length); // returned length does not include null terminator } } #if DEBUG if (length == 0) { // We never used to throw here, want to surface possible mistakes on our part int error = Marshal.GetLastWin32Error(); Debug.Assert(error == 0, $"Failed GetWindowTextW(): { new Win32Exception(error).Message }"); } #endif return title.Slice(0, length).ToString(); } public IntPtr MainWindowHandle { get { if (!_haveMainWindow) { EnsureState(State.IsLocal | State.HaveId); _mainWindowHandle = ProcessManager.GetMainWindowHandle(_processId); _haveMainWindow = true; } return _mainWindowHandle; } } private bool CloseMainWindowCore() { const int GWL_STYLE = -16; // Retrieves the window styles. const int WS_DISABLED = 0x08000000; // WindowStyle disabled. A disabled window cannot receive input from the user. const int WM_CLOSE = 0x0010; // WindowMessage close. IntPtr mainWindowHandle = MainWindowHandle; if (mainWindowHandle == (IntPtr)0) { return false; } int style = Interop.User32.GetWindowLong(mainWindowHandle, GWL_STYLE); if ((style & WS_DISABLED) != 0) { return false; } Interop.User32.PostMessageW(mainWindowHandle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); return true; } public string MainWindowTitle { get { if (_mainWindowTitle == null) { _mainWindowTitle = GetMainWindowTitle(); } return _mainWindowTitle; } } private bool IsRespondingCore() { const int WM_NULL = 0x0000; const int SMTO_ABORTIFHUNG = 0x0002; IntPtr mainWindow = MainWindowHandle; if (mainWindow == (IntPtr)0) { return true; } IntPtr result; return Interop.User32.SendMessageTimeout(mainWindow, WM_NULL, IntPtr.Zero, IntPtr.Zero, SMTO_ABORTIFHUNG, 5000, out result) != (IntPtr)0; } public bool Responding { get { if (!_haveResponding) { _responding = IsRespondingCore(); _haveResponding = true; } return _responding; } } private bool WaitForInputIdleCore(int milliseconds) { const int WAIT_OBJECT_0 = 0x00000000; const int WAIT_FAILED = unchecked((int)0xFFFFFFFF); const int WAIT_TIMEOUT = 0x00000102; bool idle; using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.SYNCHRONIZE | Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { int ret = Interop.User32.WaitForInputIdle(handle, milliseconds); switch (ret) { case WAIT_OBJECT_0: idle = true; break; case WAIT_TIMEOUT: idle = false; break; case WAIT_FAILED: default: throw new InvalidOperationException(SR.InputIdleUnkownError); } } return idle; } /// <summary>Checks whether the argument is a direct child of this process.</summary> /// <remarks> /// A child process is a process which has this process's id as its parent process id and which started after this process did. /// </remarks> private bool IsParentOf(Process possibleChild) => StartTime < possibleChild.StartTime && Id == possibleChild.ParentProcessId; /// <summary> /// Get the process's parent process id. /// </summary> private unsafe int ParentProcessId { get { Interop.NtDll.PROCESS_BASIC_INFORMATION info = default; using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { if (Interop.NtDll.NtQueryInformationProcess(handle, Interop.NtDll.PROCESSINFOCLASS.ProcessBasicInformation, &info, (uint)sizeof(Interop.NtDll.PROCESS_BASIC_INFORMATION), out _) != 0) throw new Win32Exception(SR.ProcessInformationUnavailable); return (int)info.InheritedFromUniqueProcessId; } } } private bool Equals(Process process) => Id == process.Id && StartTime == process.StartTime; private IEnumerable<Exception> KillTree() { // The process's structures will be preserved as long as a handle is held pointing to them, even if the process exits or // is terminated. A handle is held here to ensure a stable reference to the process during execution. using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION)) { return KillTree(handle); } } private IEnumerable<Exception> KillTree(SafeProcessHandle handle) { List<Exception> exceptions = new List<Exception>(); try { // Kill the process, so that no further children can be created. // // This method can return before stopping has completed. Down the road, could possibly wait for termination to complete before continuing. Kill(); } catch (InvalidOperationException) { // The process isn't in a valid state for termination (e.g. already dead), so ignore the exception // but don't give up in case children can still be enumerated. } catch (Win32Exception e) { exceptions.Add(e); } IReadOnlyList<(Process Process, SafeProcessHandle Handle)> children = GetProcessHandlePairs(p => SafePredicateTest(() => IsParentOf(p))); try { foreach ((Process Process, SafeProcessHandle Handle) child in children) { IEnumerable<Exception> exceptionsFromChild = child.Process.KillTree(child.Handle); exceptions.AddRange(exceptionsFromChild); } } finally { foreach ((Process Process, SafeProcessHandle Handle) child in children) { child.Process.Dispose(); child.Handle.Dispose(); } } return exceptions; } private IReadOnlyList<(Process Process, SafeProcessHandle Handle)> GetProcessHandlePairs(Func<Process, bool> predicate) { return GetProcesses() .Select(p => (Process: p, Handle: SafeGetHandle(p))) .Where(p => !p.Handle.IsInvalid && predicate(p.Process)) .ToList(); SafeProcessHandle SafeGetHandle(Process process) { try { return process.GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION, false); } catch (Win32Exception) { return SafeProcessHandle.InvalidHandle; } } } } }
// 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; using System.Collections.Generic; // NOTE ON FIELD RENAMES: // This type is inspected internally by .NET Native Debugger components. ANY changes to field names // (including private and nested public fields) are considered a breaking change and should not be done without // similar changes to those debugger components at the same time. namespace System.Collections.Generic { /*============================================================ ** ** Class: LowLevelDictionary<TKey, TValue> ** ** Private version of Dictionary<> for internal System.Private.CoreLib use. This ** permits sharing more source between BCL and System.Private.CoreLib (as well as the ** fact that Dictionary<> is just a useful class in general.) ** ** This does not strive to implement the full api surface area ** (but any portion it does implement should match the real Dictionary<>'s ** behavior.) ** ===========================================================*/ #if TYPE_LOADER_IMPLEMENTATION [System.Runtime.CompilerServices.ForceDictionaryLookups] #endif internal class LowLevelDictionary<TKey, TValue> { private const int DefaultSize = 17; public LowLevelDictionary() : this(DefaultSize, new DefaultComparer<TKey>()) { } public LowLevelDictionary(int capacity) : this(capacity, new DefaultComparer<TKey>()) { } public LowLevelDictionary(IEqualityComparer<TKey> comparer) : this(DefaultSize, comparer) { } public LowLevelDictionary(int capacity, IEqualityComparer<TKey> comparer) { _comparer = comparer; Clear(capacity); } public int Count { get { return _numEntries; } } public TValue this[TKey key] { get { if (key == null) throw new ArgumentNullException("key"); Entry entry = Find(key); if (entry == null) throw new KeyNotFoundException(); return entry.m_value; } set { if (key == null) throw new ArgumentNullException("key"); _version++; Entry entry = Find(key); if (entry != null) entry.m_value = value; else UncheckedAdd(key, value); } } public bool TryGetValue(TKey key, out TValue value) { value = default(TValue); if (key == null) throw new ArgumentNullException("key"); Entry entry = Find(key); if (entry != null) { value = entry.m_value; return true; } return false; } public void Add(TKey key, TValue value) { if (key == null) throw new ArgumentNullException("key"); Entry entry = Find(key); if (entry != null) throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key)); _version++; UncheckedAdd(key, value); } public void Clear(int capacity = DefaultSize) { _version++; _buckets = new Entry[capacity]; _numEntries = 0; } public bool Remove(TKey key) { if (key == null) throw new ArgumentNullException("key"); int bucket = GetBucket(key); Entry prev = null; Entry entry = _buckets[bucket]; while (entry != null) { if (_comparer.Equals(key, entry.m_key)) { if (prev == null) { _buckets[bucket] = entry.m_next; } else { prev.m_next = entry.m_next; } _version++; _numEntries--; return true; } prev = entry; entry = entry.m_next; } return false; } internal TValue LookupOrAdd(TKey key, TValue value) { Entry entry = Find(key); if (entry != null) return entry.m_value; UncheckedAdd(key, value); return value; } private Entry Find(TKey key) { int bucket = GetBucket(key); Entry entry = _buckets[bucket]; while (entry != null) { if (_comparer.Equals(key, entry.m_key)) return entry; entry = entry.m_next; } return null; } private Entry UncheckedAdd(TKey key, TValue value) { Entry entry = new Entry(); entry.m_key = key; entry.m_value = value; int bucket = GetBucket(key); entry.m_next = _buckets[bucket]; _buckets[bucket] = entry; _numEntries++; if (_numEntries > (_buckets.Length * 2)) ExpandBuckets(); return entry; } private void ExpandBuckets() { try { int newNumBuckets = _buckets.Length * 2 + 1; Entry[] newBuckets = new Entry[newNumBuckets]; for (int i = 0; i < _buckets.Length; i++) { Entry entry = _buckets[i]; while (entry != null) { Entry nextEntry = entry.m_next; int bucket = GetBucket(entry.m_key, newNumBuckets); entry.m_next = newBuckets[bucket]; newBuckets[bucket] = entry; entry = nextEntry; } } _buckets = newBuckets; } catch (OutOfMemoryException) { } } private int GetBucket(TKey key, int numBuckets = 0) { int h = _comparer.GetHashCode(key); h &= 0x7fffffff; return (h % (numBuckets == 0 ? _buckets.Length : numBuckets)); } #if TYPE_LOADER_IMPLEMENTATION [System.Runtime.CompilerServices.ForceDictionaryLookups] #endif private sealed class Entry { public TKey m_key; public TValue m_value; public Entry m_next; } private Entry[] _buckets; private int _numEntries; private int _version; private IEqualityComparer<TKey> _comparer; // This comparator is used if no comparator is supplied. It emulates the behavior of EqualityComparer<T>.Default. #if TYPE_LOADER_IMPLEMENTATION [System.Runtime.CompilerServices.ForceDictionaryLookups] #endif private sealed class DefaultComparer<T> : IEqualityComparer<T> { public bool Equals(T x, T y) { if (x == null) return y == null; IEquatable<T> iequatable = x as IEquatable<T>; if (iequatable != null) return iequatable.Equals(y); return ((object)x).Equals(y); } public int GetHashCode(T obj) { return ((object)obj).GetHashCode(); } } #if TYPE_LOADER_IMPLEMENTATION [System.Runtime.CompilerServices.ForceDictionaryLookups] #endif protected sealed class LowLevelDictEnumerator : IEnumerator<KeyValuePair<TKey, TValue>> { public LowLevelDictEnumerator(LowLevelDictionary<TKey, TValue> dict) { _dict = dict; _version = _dict._version; Entry[] entries = new Entry[_dict._numEntries]; int dst = 0; for (int bucket = 0; bucket < _dict._buckets.Length; bucket++) { Entry entry = _dict._buckets[bucket]; while (entry != null) { entries[dst++] = entry; entry = entry.m_next; } } _entries = entries; Reset(); } public KeyValuePair<TKey, TValue> Current { get { if (_version != _dict._version) throw new InvalidOperationException("InvalidOperation_EnumFailedVersion"); if (_curPosition == -1 || _curPosition == _entries.Length) throw new InvalidOperationException("InvalidOperation_EnumOpCantHappen"); Entry entry = _entries[_curPosition]; return new KeyValuePair<TKey, TValue>(entry.m_key, entry.m_value); } } public void Dispose() { } public bool MoveNext() { if (_version != _dict._version) throw new InvalidOperationException("InvalidOperation_EnumFailedVersion"); if (_curPosition != _entries.Length) _curPosition++; bool anyMore = (_curPosition != _entries.Length); return anyMore; } object IEnumerator.Current { get { KeyValuePair<TKey, TValue> kv = Current; return kv; } } public void Reset() { if (_version != _dict._version) throw new InvalidOperationException("InvalidOperation_EnumFailedVersion"); _curPosition = -1; } private LowLevelDictionary<TKey, TValue> _dict; private Entry[] _entries; private int _curPosition; private int _version; } } /// <summary> /// LowLevelDictionary when enumeration is needed /// </summary> internal sealed class LowLevelDictionaryWithIEnumerable<TKey, TValue> : LowLevelDictionary<TKey, TValue>, IEnumerable<KeyValuePair<TKey, TValue>> { public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return new LowLevelDictEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { IEnumerator<KeyValuePair<TKey, TValue>> ie = GetEnumerator(); return ie; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Localization; using OrchardCore.Admin; using OrchardCore.Deployment.Indexes; using OrchardCore.Deployment.ViewModels; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Navigation; using OrchardCore.Routing; using OrchardCore.Settings; using YesSql; using YesSql.Services; namespace OrchardCore.Deployment.Controllers { [Admin] public class DeploymentPlanController : Controller { private readonly IAuthorizationService _authorizationService; private readonly IDisplayManager<DeploymentStep> _displayManager; private readonly IEnumerable<IDeploymentStepFactory> _factories; private readonly ISession _session; private readonly ISiteService _siteService; private readonly INotifier _notifier; private readonly IUpdateModelAccessor _updateModelAccessor; private readonly IStringLocalizer S; private readonly IHtmlLocalizer H; private readonly dynamic New; public DeploymentPlanController( IAuthorizationService authorizationService, IDisplayManager<DeploymentStep> displayManager, IEnumerable<IDeploymentStepFactory> factories, ISession session, ISiteService siteService, IShapeFactory shapeFactory, IStringLocalizer<DeploymentPlanController> stringLocalizer, IHtmlLocalizer<DeploymentPlanController> htmlLocalizer, INotifier notifier, IUpdateModelAccessor updateModelAccessor) { _displayManager = displayManager; _factories = factories; _authorizationService = authorizationService; _session = session; _siteService = siteService; _notifier = notifier; _updateModelAccessor = updateModelAccessor; New = shapeFactory; S = stringLocalizer; H = htmlLocalizer; } public async Task<IActionResult> Index(DeploymentPlanIndexOptions options, PagerParameters pagerParameters) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan)) { return Forbid(); } if (!await _authorizationService.AuthorizeAsync(User, Permissions.Export)) { return Forbid(); } var siteSettings = await _siteService.GetSiteSettingsAsync(); var pager = new Pager(pagerParameters, siteSettings.PageSize); // default options if (options == null) { options = new DeploymentPlanIndexOptions(); } var deploymentPlans = _session.Query<DeploymentPlan, DeploymentPlanIndex>(); if (!string.IsNullOrWhiteSpace(options.Search)) { deploymentPlans = deploymentPlans.Where(dp => dp.Name.Contains(options.Search)); } var count = await deploymentPlans.CountAsync(); var results = await deploymentPlans .Skip(pager.GetStartIndex()) .Take(pager.PageSize) .ListAsync(); // Maintain previous route data when generating page links var routeData = new RouteData(); routeData.Values.Add("Options.Search", options.Search); var pagerShape = (await New.Pager(pager)).TotalItemCount(count).RouteData(routeData); var model = new DeploymentPlanIndexViewModel { DeploymentPlans = results.Select(x => new DeploymentPlanEntry { DeploymentPlan = x }).ToList(), Options = options, Pager = pagerShape }; model.Options.DeploymentPlansBulkAction = new List<SelectListItem>() { new SelectListItem() { Text = S["Delete"], Value = nameof(DeploymentPlansBulkAction.Delete) } }; return View(model); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] public ActionResult IndexFilterPOST(DeploymentPlanIndexViewModel model) { return RedirectToAction(nameof(Index), new RouteValueDictionary { { "Options.Search", model.Options.Search } }); } [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.BulkAction")] public async Task<ActionResult> IndexBulkActionPOST(DeploymentPlanIndexOptions options, IEnumerable<int> itemIds) { if (itemIds?.Count() > 0) { var checkedItems = await _session.Query<DeploymentPlan, DeploymentPlanIndex>().Where(x => x.DocumentId.IsIn(itemIds)).ListAsync(); switch (options.BulkAction) { case DeploymentPlansBulkAction.None: break; case DeploymentPlansBulkAction.Delete: foreach (var item in checkedItems) { _session.Delete(item); _notifier.Success(H["Deployment plan {0} successfully deleted.", item.Name]); } break; default: throw new ArgumentOutOfRangeException(); } } return RedirectToAction(nameof(Index)); } public async Task<IActionResult> Display(int id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan)) { return Forbid(); } var deploymentPlan = await _session.GetAsync<DeploymentPlan>(id); if (deploymentPlan == null) { return NotFound(); } var items = new List<dynamic>(); foreach (var step in deploymentPlan.DeploymentSteps) { dynamic item = await _displayManager.BuildDisplayAsync(step, _updateModelAccessor.ModelUpdater, "Summary"); item.DeploymentStep = step; items.Add(item); } var thumbnails = new Dictionary<string, dynamic>(); foreach (var factory in _factories) { var step = factory.Create(); dynamic thumbnail = await _displayManager.BuildDisplayAsync(step, _updateModelAccessor.ModelUpdater, "Thumbnail"); thumbnail.DeploymentStep = step; thumbnails.Add(factory.Name, thumbnail); } var model = new DisplayDeploymentPlanViewModel { DeploymentPlan = deploymentPlan, Items = items, Thumbnails = thumbnails, }; return View(model); } public async Task<IActionResult> Create() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan)) { return Forbid(); } var model = new CreateDeploymentPlanViewModel(); return View(model); } [HttpPost] public async Task<IActionResult> Create(CreateDeploymentPlanViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan)) { return Forbid(); } if (ModelState.IsValid) { if (String.IsNullOrWhiteSpace(model.Name)) { ModelState.AddModelError(nameof(CreateDeploymentPlanViewModel.Name), S["The name is mandatory."]); } } if (ModelState.IsValid) { var deploymentPlan = new DeploymentPlan { Name = model.Name }; _session.Save(deploymentPlan); return RedirectToAction(nameof(Index)); } // If we got this far, something failed, redisplay form return View(model); } public async Task<IActionResult> Edit(int id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan)) { return Forbid(); } var deploymentPlan = await _session.GetAsync<DeploymentPlan>(id); if (deploymentPlan == null) { return NotFound(); } var model = new EditDeploymentPlanViewModel { Id = deploymentPlan.Id, Name = deploymentPlan.Name }; return View(model); } [HttpPost] public async Task<IActionResult> Edit(EditDeploymentPlanViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan)) { return Forbid(); } var deploymentPlan = await _session.GetAsync<DeploymentPlan>(model.Id); if (deploymentPlan == null) { return NotFound(); } if (ModelState.IsValid) { if (String.IsNullOrWhiteSpace(model.Name)) { ModelState.AddModelError(nameof(EditDeploymentPlanViewModel.Name), S["The name is mandatory."]); } } if (ModelState.IsValid) { deploymentPlan.Name = model.Name; _session.Save(deploymentPlan); _notifier.Success(H["Deployment plan updated successfully"]); return RedirectToAction(nameof(Index)); } // If we got this far, something failed, redisplay form return View(model); } [HttpPost] public async Task<IActionResult> Delete(int id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan)) { return Forbid(); } var deploymentPlan = await _session.GetAsync<DeploymentPlan>(id); if (deploymentPlan == null) { return NotFound(); } _session.Delete(deploymentPlan); _notifier.Success(H["Deployment plan deleted successfully"]); return RedirectToAction(nameof(Index)); } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Microsoft.CSharp; using Xunit; using NLog.Config; using NLog.UnitTests.Mocks; public sealed class ConfigFileLocatorTests : NLogTestBase, IDisposable { private readonly string _tempDirectory; public ConfigFileLocatorTests() { _tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(_tempDirectory); } void IDisposable.Dispose() { if (Directory.Exists(_tempDirectory)) Directory.Delete(_tempDirectory, true); } [Fact] public void GetCandidateConfigTest() { var candidateConfigFilePaths = XmlLoggingConfiguration.GetCandidateConfigFilePaths(); Assert.NotNull(candidateConfigFilePaths); var count = candidateConfigFilePaths.Count(); Assert.NotEqual(0, count); } [Fact] public void GetCandidateConfigTest_list_is_readonly() { Assert.Throws<NotSupportedException>(() => { var list = new List<string> { "c:\\global\\temp.config" }; XmlLoggingConfiguration.SetCandidateConfigFilePaths(list); var candidateConfigFilePaths = XmlLoggingConfiguration.GetCandidateConfigFilePaths(); var list2 = candidateConfigFilePaths as IList; list2.Add("test"); }); } [Fact] public void SetCandidateConfigTest() { var list = new List<string> { "c:\\global\\temp.config" }; XmlLoggingConfiguration.SetCandidateConfigFilePaths(list); Assert.Single(XmlLoggingConfiguration.GetCandidateConfigFilePaths()); //no side effects list.Add("c:\\global\\temp2.config"); Assert.Single(XmlLoggingConfiguration.GetCandidateConfigFilePaths()); } [Fact] public void ResetCandidateConfigTest() { var countBefore = XmlLoggingConfiguration.GetCandidateConfigFilePaths().Count(); var list = new List<string> { "c:\\global\\temp.config" }; XmlLoggingConfiguration.SetCandidateConfigFilePaths(list); Assert.Single(XmlLoggingConfiguration.GetCandidateConfigFilePaths()); XmlLoggingConfiguration.ResetCandidateConfigFilePath(); Assert.Equal(countBefore, XmlLoggingConfiguration.GetCandidateConfigFilePaths().Count()); } [Theory] [MemberData(nameof(GetConfigFile_absolutePath_loads_testData))] public void GetConfigFile_absolutePath_loads(string filename, string accepts, string expected, string baseDir) { // Arrange var appEnvMock = new AppEnvironmentMock(f => f == accepts, f => null) { AppDomainBaseDirectory = baseDir }; var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); // Act var result = fileLoader.GetConfigFile(filename); // Assert Assert.Equal(expected, result); } public static IEnumerable<object[]> GetConfigFile_absolutePath_loads_testData() { var d = Path.DirectorySeparatorChar; var baseDir = Path.GetTempPath(); var dirInBaseDir = $"{baseDir}dir1"; yield return new object[] { $"{baseDir}configfile", $"{baseDir}configfile", $"{baseDir}configfile", dirInBaseDir }; yield return new object[] { "nlog.config", $"{baseDir}dir1{d}nlog.config", $"{baseDir}dir1{d}nlog.config", dirInBaseDir }; //exists yield return new object[] { "nlog.config", $"{baseDir}dir1{d}nlog2.config", "nlog.config", dirInBaseDir }; //not existing, fallback } [Fact] public void LoadConfigFile_EmptyEnvironment_UseCurrentDirectory() { // Arrange var appEnvMock = new AppEnvironmentMock(f => true, f => null); var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); // Act var result = fileLoader.GetDefaultCandidateConfigFilePaths().ToList(); // Assert loading from current-directory and from nlog-assembly-directory if (NLog.Internal.PlatformDetector.IsWin32) Assert.Equal(2, result.Count); // Case insensitive Assert.Equal("NLog.config", result.First(), StringComparer.OrdinalIgnoreCase); Assert.Contains("NLog.dll.nlog", result.Last(), StringComparison.OrdinalIgnoreCase); } [Fact] public void LoadConfigFile_NetCoreUnpublished_UseEntryDirectory() { // Arrange var tmpDir = Path.GetTempPath(); var appEnvMock = new AppEnvironmentMock(f => true, f => null) { AppDomainBaseDirectory = Path.Combine(tmpDir, "BaseDir"), #if NETSTANDARD AppDomainConfigurationFile = string.Empty, // NetCore style #else AppDomainConfigurationFile = Path.Combine(tmpDir, "EntryDir", "Entry.exe.config"), #endif CurrentProcessFilePath = Path.Combine(tmpDir, "ProcessDir", "Process.exe"),// NetCore dotnet.exe EntryAssemblyLocation = Path.Combine(tmpDir, "EntryDir"), EntryAssemblyFileName = "Entry.dll" }; var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); // Act var result = fileLoader.GetDefaultCandidateConfigFilePaths().ToList(); // Assert base-directory + entry-directory + nlog-assembly-directory AssertResult(tmpDir, "EntryDir", "EntryDir", "Entry", result); } [Fact] public void LoadConfigFile_NetCorePublished_UseProcessDirectory() { // Arrange var tmpDir = Path.GetTempPath(); var appEnvMock = new AppEnvironmentMock(f => true, f => null) { AppDomainBaseDirectory = Path.Combine(tmpDir, "BaseDir"), #if NETSTANDARD AppDomainConfigurationFile = string.Empty, // NetCore style #else AppDomainConfigurationFile = Path.Combine(tmpDir, "ProcessDir", "Process.exe.config"), #endif CurrentProcessFilePath = Path.Combine(tmpDir, "ProcessDir", "Process.exe"), // NetCore published exe EntryAssemblyLocation = Path.Combine(tmpDir, "ProcessDir"), EntryAssemblyFileName = "Entry.dll" }; var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); // Act var result = fileLoader.GetDefaultCandidateConfigFilePaths().ToList(); // Assert base-directory + process-directory + nlog-assembly-directory AssertResult(tmpDir, "ProcessDir", "ProcessDir", "Process", result); } [Fact] public void LoadConfigFile_NetCoreSingleFilePublish_IgnoreTempDirectory() { // Arrange var tmpDir = Path.GetTempPath(); var appEnvMock = new AppEnvironmentMock(f => true, f => null) { AppDomainBaseDirectory = Path.Combine(tmpDir, "BaseDir"), #if NETSTANDARD AppDomainConfigurationFile = string.Empty, // NetCore style #else AppDomainConfigurationFile = Path.Combine(tmpDir, "ProcessDir", "Process.exe.config"), #endif CurrentProcessFilePath = Path.Combine(tmpDir, "ProcessDir", "Process.exe"), // NetCore published exe EntryAssemblyLocation = Path.Combine(tmpDir, "TempProcessDir"), UserTempFilePath = Path.Combine(tmpDir, "TempProcessDir"), EntryAssemblyFileName = "Entry.dll" }; var fileLoader = new LoggingConfigurationFileLoader(appEnvMock); // Act var result = fileLoader.GetDefaultCandidateConfigFilePaths().ToList(); // Assert base-directory + process-directory + nlog-assembly-directory AssertResult(tmpDir, "TempProcessDir", "ProcessDir", "Process", result); } private static void AssertResult(string tmpDir, string appDir, string processDir, string appName, List<string> result) { if (NLog.Internal.PlatformDetector.IsWin32) { #if NETSTANDARD Assert.Equal(5, result.Count); // Case insensitive #else Assert.Equal(4, result.Count); // Case insensitive #endif } Assert.Equal(Path.Combine(tmpDir, "BaseDir", "NLog.config"), result.First(), StringComparer.OrdinalIgnoreCase); Assert.Contains(Path.Combine(tmpDir, appDir, "NLog.config"), result, StringComparer.OrdinalIgnoreCase); Assert.Contains(Path.Combine(tmpDir, processDir, appName + ".exe.nlog"), result, StringComparer.OrdinalIgnoreCase); #if NETSTANDARD Assert.Contains(Path.Combine(tmpDir, appDir, "Entry.dll.nlog"), result, StringComparer.OrdinalIgnoreCase); #endif Assert.Contains("NLog.dll.nlog", result.Last(), StringComparison.OrdinalIgnoreCase); } #if !NETSTANDARD private string appConfigContents = @" <configuration> <configSections> <section name='nlog' type='NLog.Config.ConfigSectionHandler, NLog' requirePermission='false' /> </configSections> <nlog> <targets> <target name='c' type='Console' layout='AC ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> </configuration> "; private string appNLogContents = @" <nlog> <targets> <target name='c' type='Console' layout='AN ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> "; private string nlogConfigContents = @" <nlog> <targets> <target name='c' type='Console' layout='NLC ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> "; private string nlogDllNLogContents = @" <nlog> <targets> <target name='c' type='Console' layout='NDN ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> "; private string appConfigOutput = "--BEGIN--|AC InfoMsg|AC WarnMsg|AC ErrorMsg|AC FatalMsg|--END--|"; private string appNLogOutput = "--BEGIN--|AN InfoMsg|AN WarnMsg|AN ErrorMsg|AN FatalMsg|--END--|"; private string nlogConfigOutput = "--BEGIN--|NLC InfoMsg|NLC WarnMsg|NLC ErrorMsg|NLC FatalMsg|--END--|"; private string nlogDllNLogOutput = "--BEGIN--|NDN InfoMsg|NDN WarnMsg|NDN ErrorMsg|NDN FatalMsg|--END--|"; private string missingConfigOutput = "--BEGIN--|--END--|"; [Fact] public void MissingConfigFileTest() { string output = RunTest(); Assert.Equal(missingConfigOutput, output); } [Fact] public void NLogDotConfigTest() { File.WriteAllText(Path.Combine(_tempDirectory, "NLog.config"), nlogConfigContents); string output = RunTest(); Assert.Equal(nlogConfigOutput, output); } [Fact] public void NLogDotDllDotNLogTest() { File.WriteAllText(Path.Combine(_tempDirectory, "NLog.dll.nlog"), nlogDllNLogContents); string output = RunTest(); Assert.Equal(nlogDllNLogOutput, output); } [Fact] public void NLogDotDllDotNLogInDirectoryWithSpaces() { File.WriteAllText(Path.Combine(_tempDirectory, "NLog.dll.nlog"), nlogDllNLogContents); string output = RunTest(); Assert.Equal(nlogDllNLogOutput, output); } [Fact] public void AppDotConfigTest() { File.WriteAllText(Path.Combine(_tempDirectory, "ConfigFileLocator.exe.config"), appConfigContents); string output = RunTest(); Assert.Equal(appConfigOutput, output); } [Fact] public void AppDotNLogTest() { File.WriteAllText(Path.Combine(_tempDirectory, "ConfigFileLocator.exe.nlog"), appNLogContents); string output = RunTest(); Assert.Equal(appNLogOutput, output); } [Fact] public void PrecedenceTest() { var precedence = new[] { new { File = "ConfigFileLocator.exe.config", Contents = appConfigContents, Output = appConfigOutput }, new { File = "NLog.config", Contents = nlogConfigContents, Output = nlogConfigOutput }, new { File = "ConfigFileLocator.exe.nlog", Contents = appNLogContents, Output = appNLogOutput }, new { File = "NLog.dll.nlog", Contents = nlogDllNLogContents, Output = nlogDllNLogOutput }, }; // deploy all files foreach (var p in precedence) { File.WriteAllText(Path.Combine(_tempDirectory, p.File), p.Contents); } string output; // walk files in precedence order and delete config files foreach (var p in precedence) { output = RunTest(); Assert.Equal(p.Output, output); File.Delete(Path.Combine(_tempDirectory, p.File)); } output = RunTest(); Assert.Equal(missingConfigOutput, output); } private string RunTest() { string sourceCode = @" using System; using System.Reflection; using NLog; class C1 { private static ILogger logger = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { Console.WriteLine(""--BEGIN--""); logger.Trace(""TraceMsg""); logger.Debug(""DebugMsg""); logger.Info(""InfoMsg""); logger.Warn(""WarnMsg""); logger.Error(""ErrorMsg""); logger.Fatal(""FatalMsg""); Console.WriteLine(""--END--""); } }"; var provider = new CSharpCodeProvider(); var options = new System.CodeDom.Compiler.CompilerParameters(); options.OutputAssembly = Path.Combine(_tempDirectory, "ConfigFileLocator.exe"); options.GenerateExecutable = true; options.ReferencedAssemblies.Add(typeof(ILogger).Assembly.Location); options.IncludeDebugInformation = true; if (!File.Exists(options.OutputAssembly)) { var results = provider.CompileAssemblyFromSource(options, sourceCode); Assert.False(results.Errors.HasWarnings); Assert.False(results.Errors.HasErrors); File.Copy(typeof(ILogger).Assembly.Location, Path.Combine(_tempDirectory, "NLog.dll")); } return RunAndRedirectOutput(options.OutputAssembly); } public static string RunAndRedirectOutput(string exeFile) { using (var proc = new Process()) { #if MONO var sb = new StringBuilder(); sb.AppendFormat("\"{0}\" ", exeFile); proc.StartInfo.Arguments = sb.ToString(); proc.StartInfo.FileName = "mono"; proc.StartInfo.StandardOutputEncoding = Encoding.UTF8; proc.StartInfo.StandardErrorEncoding = Encoding.UTF8; #else proc.StartInfo.FileName = exeFile; #endif proc.StartInfo.UseShellExecute = false; proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal; proc.StartInfo.RedirectStandardInput = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; proc.Start(); proc.WaitForExit(); Assert.Equal(string.Empty, proc.StandardError.ReadToEnd()); return proc.StandardOutput.ReadToEnd().Replace("\r", "").Replace("\n", "|"); } } #endif } }
// This is an open source non-commercial project. Dear PVS-Studio, please check it. PVS-Studio Static // Code Analyzer for C, C++ and C#: http://www.viva64.com namespace EOpt.Math.Optimization.OOOpt { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Help; using Math.Random; /// <summary> /// Optimization method GEM. /// </summary> public class GEMOptimizer : IBaseOptimizer<GEMParams, IOOOptProblem>, IOOOptimizer<GEMParams> { private Agent _solution; private PointND _dosd, _dgrs, _drnd; /// <summary> /// Grenades. /// </summary> private List<Agent> _grenades; private INormalGen _normalRand; private GEMParams _parameters; private double _radiusGrenade, _radiusExplosion, _radiusInitial, _mosd; private IReadOnlyList<double> _lowerBounds; private IReadOnlyList<double> _upperBounds; private Func<IReadOnlyList<double>, double> _targetFuncWithTransformedCoords; private Func<IReadOnlyList<double>, double> _originalTargetFunction; /// <summary> /// Shrapnels. /// </summary> private LinkedList<Agent>[] _shrapnels; // The temporary array has a 'Length' is equal 'dimension'. Used in the calculation the value // of the target function. private double[] _tempArray; private IContUniformGen _uniformRand; private Agent _xcur, _xosd, _xrnd; /// <summary> /// Sort by ascending. /// </summary> private void ArrangeGrenades() { _grenades.Sort((x, y) => x.Objs[0].CompareTo(y.Objs[0])); } private void FindBestPosition(int WhichGrenade) { // Find shrapnel with a minimum value of the target function. _xrnd = null; if (_shrapnels[WhichGrenade].Count != 0) { _xrnd = _shrapnels[WhichGrenade].First.Value; foreach (Agent shrapnel in _shrapnels[WhichGrenade]) { if (shrapnel.Objs[0] < _xrnd.Objs[0]) { _xrnd = shrapnel; } } } Agent bestPosition = null; // Find best position with a minimum value of the target function among: xcur, xrnd, xosd. if (_xcur == null && _xrnd != null) { bestPosition = _xrnd; } else if (_xcur != null && _xrnd == null) { bestPosition = _xcur; } else if (_xcur != null && _xrnd != null) { bestPosition = _xrnd.Objs[0] < _xcur.Objs[0] ? _xrnd : _xcur; } if (_xosd != null && bestPosition != null) { bestPosition = bestPosition.Objs[0] < _xosd.Objs[0] ? bestPosition : _xosd; } else if (_xosd != null && bestPosition == null) { bestPosition = _xosd; } // If exist a best position then move grenade. if (bestPosition != null) { _grenades[WhichGrenade] = bestPosition; } _xosd = null; _xrnd = null; _xcur = null; _dosd = null; _shrapnels[WhichGrenade].Clear(); } /// <summary> /// Calculate target function for the grenades. /// </summary> private void EvalFunctionForGrenades() { for (int i = 0; i < _parameters.NGrenade; i++) { _grenades[i].Eval(_targetFuncWithTransformedCoords); } } /// <summary> /// Coordinates transformation: [-1; 1] -&gt; [LowerBounds[i]; UpperBounds[i]]. /// </summary> /// <param name="X"> Input coordinates. </param> /// <param name="LowerBounds"></param> /// <param name="UpperBounds"></param> private static void TransformCoord(double[] X, IReadOnlyList<double> LowerBounds, IReadOnlyList<double> UpperBounds) { for (int i = 0; i < LowerBounds.Count; i++) { X[i] = 0.5 * (LowerBounds[i] + UpperBounds[i] + (UpperBounds[i] - LowerBounds[i]) * X[i]); } } /// <summary> /// Calculate target function for the shrapnels. Shrapnels from grenade under number <paramref name="WhichGrenade"/>. /// </summary> private void EvalFunctionForShrapnels(int WhichGrenade) { foreach (Agent shrapnel in _shrapnels[WhichGrenade]) { shrapnel.Eval(_targetFuncWithTransformedCoords); } } /// <summary> /// Find best solution. /// </summary> private void FindSolution(IOOOptProblem Problem) { double fMin = _grenades[0].Objs[0]; int indexMin = 0; for (int i = 1; i < _grenades.Count; i++) { if (_grenades[i].Objs[0] < fMin) { fMin = _grenades[i].Objs[0]; indexMin = i; } } // Solution has coordinates in the range [-1; 1]. _solution.SetAt(_grenades[indexMin]); for (int i = 0; i < _solution.Point.Count; i++) { _tempArray[i] = _solution.Point[i]; } TransformCoord(_tempArray, Problem.LowerBounds, Problem.UpperBounds); for (int i = 0; i < _solution.Point.Count; i++) { _solution.Point[i] = _tempArray[i]; } } /// <summary> /// Determine shrapnels position. /// </summary> /// <param name="WhichGrenade"></param> /// <param name="NumIter"> </param> private void GenerateShrapneles(IOOOptProblem Problem, int WhichGrenade, int NumIter) { // Determine OSD and Xosd. if (NumIter <= 0.1 * _parameters.Imax && WhichGrenade < _parameters.DesiredMin) { FindOSD(WhichGrenade, Problem.LowerBounds.Count); } GenerateShrapnelesForGrenade(WhichGrenade, Problem.LowerBounds.Count); } private void GenerateShrapnelesForGrenade(int WhichGrenade, int Dimension) { double p = Math.Max(1.0 / Dimension, Math.Log10(_radiusGrenade / _radiusExplosion) / Math.Log10(_parameters.Pts)); if (CheckDouble.GetTypeValue(p) != DoubleTypeValue.Valid) { p = 0.5; } double randomValue1, randomValue2; bool isShrapnelAdd = true; PointND tempPoint = null; // Generating shrapnels. for (int i = 0; i < _parameters.NShrapnel; i++) { // Reuse an allocated memory, if 'tempPoint' was not added to the array, otherwise // allocate a new memory. if (isShrapnelAdd) { tempPoint = new PointND(0.0, Dimension); } randomValue1 = _uniformRand.URandVal(0, 1); // Random search direction. for (int w = 0; w < _drnd.Count; w++) { _drnd[w] = _normalRand.NRandVal(0, 1); } _drnd.MultiplyByInplace(1 / _drnd.Norm()); // If exist OSD. if (_dosd != null) { randomValue2 = _uniformRand.URandVal(0, 1); for (int coordIndex = 0; coordIndex < _dgrs.Count; coordIndex++) { _dgrs[coordIndex] = _mosd * randomValue1 * _dosd[coordIndex] + (1 - _mosd) * randomValue2 * _drnd[coordIndex]; } _dgrs.MultiplyByInplace(1 / _dgrs.Norm()); randomValue1 = Math.Pow(randomValue1, p) * _radiusExplosion; for (int coordIndex = 0; coordIndex < _dgrs.Count; coordIndex++) { tempPoint[coordIndex] = _grenades[WhichGrenade].Point[coordIndex] + randomValue1 * _dgrs[coordIndex]; } } else { randomValue1 = Math.Pow(randomValue1, p) * _radiusExplosion; for (int coordIndex = 0; coordIndex < _dgrs.Count; coordIndex++) { tempPoint[coordIndex] = _grenades[WhichGrenade].Point[coordIndex] + randomValue1 * _drnd[coordIndex]; } } double randNum = 0.0, largeComp = 0.0; // Out of range [-1; 1]^n. for (int j = 0; j < Dimension; j++) { if (tempPoint[j] < -1 || tempPoint[j] > 1) { randNum = _uniformRand.URandVal(0, 1); largeComp = tempPoint.Max(num => Math.Abs(num)); double normPos = 0.0; for (int coordIndex = 0; coordIndex < tempPoint.Count; coordIndex++) { normPos = tempPoint[coordIndex] / largeComp; tempPoint[coordIndex] = randNum * (normPos - _grenades[WhichGrenade].Point[coordIndex]) + _grenades[WhichGrenade].Point[coordIndex]; } break; } } double dist = 0.0; // Calculate distance to grenades. for (int idxGren = 0; idxGren < _parameters.NGrenade; idxGren++) { if (idxGren != WhichGrenade) { dist = PointND.Distance(tempPoint, _grenades[idxGren].Point); // Shrapnel does not accept (it is too near to other grenades). if (dist <= _radiusGrenade) { isShrapnelAdd = false; break; } } } if (isShrapnelAdd) { _shrapnels[WhichGrenade].AddLast(new Agent(tempPoint, new PointND(0.0, 1))); } } } private double TargetFunctionWithTransformedCoords(IReadOnlyList<double> Point) { for (int i = 0; i < Point.Count; i++) { _tempArray[i] = Point[i]; } TransformCoord(_tempArray, _lowerBounds, _upperBounds); return _originalTargetFunction(_tempArray); } /// <summary> /// Searching OSD and Xosd position. /// </summary> /// <param name="WhichGrenade"></param> /// <param name="Dimension"></param> private void FindOSD(int WhichGrenade, int Dimension) { LinkedList<Agent> ortogonalArray = new LinkedList<Agent>(); // Generate 2 * n shrapnels along coordinate axis. 1 in positive direction. 1 in negative direction. bool isAddToList = false; Agent tempAgent = new Agent(Dimension, 1); bool isPosDirection = true; for (int i = 0; i < 2 * Dimension; i++) { // Reuse an allocated memory, if 'tempAgent' was not added to the array, otherwise // allocate a new memory. if (isAddToList) { tempAgent = new Agent(Dimension, 1); } isAddToList = true; tempAgent.Point.SetAt(_grenades[WhichGrenade].Point); // The positive direction along the coordinate axis. if (isPosDirection) { if (CmpDouble.AlmostEqual(_grenades[WhichGrenade].Point[i / 2], 1, Exponent: 1)) { tempAgent.Point[i / 2] = 1; } else { tempAgent.Point[i / 2] = _uniformRand.URandVal(_grenades[WhichGrenade].Point[i / 2], 1); } } // The negative direction along the coordinate axis. else { if (CmpDouble.AlmostEqual(_grenades[WhichGrenade].Point[i / 2], -1, Exponent: 1)) { tempAgent.Point[i / 2] = -1; } else { tempAgent.Point[i / 2] = _uniformRand.URandVal(-1, _grenades[WhichGrenade].Point[i / 2]); } } // Change direction. isPosDirection = !isPosDirection; // If shrapnel and grenade too near, then shrapnel deleted. for (int j = 0; j < _parameters.NGrenade; j++) { if (j != WhichGrenade) { if (PointND.Distance(tempAgent.Point, _grenades[j].Point) <= _radiusGrenade) { isAddToList = false; break; } } } if (isAddToList) { tempAgent.Eval(_targetFuncWithTransformedCoords); ortogonalArray.AddLast(tempAgent); } } // Determine position Xosd. _xosd = null; if (ortogonalArray.Count != 0) { _xosd = ortogonalArray.First.Value; foreach (Agent item in ortogonalArray) { if (item.Objs[0] < _xosd.Objs[0]) { _xosd = item; } } } // Determine position Xcur. _xcur = _grenades[WhichGrenade]; // If grenade does not be in a neighborhood of the other grenades, then xcur = null. for (int j = 0; j < _parameters.NGrenade; j++) { if (j != WhichGrenade) { if (PointND.Distance(_grenades[j].Point, _grenades[WhichGrenade].Point) <= _radiusGrenade) { _xcur = null; break; } } } // Vector dosd. _dosd = _xosd == null ? null : _xosd.Point - _grenades[WhichGrenade].Point; // Normalization vector. if (_dosd != null) { double norm = _dosd.Norm(); if (CmpDouble.AlmostEqual(norm, 0.0, 2)) { _dosd = null; } else { _dosd.MultiplyByInplace(1 / norm); } } } /// <summary> /// Create grenades. /// </summary> /// <param name="LowerBounds"></param> /// <param name="UpperBounds"></param> private void InitAgents(IReadOnlyList<double> LowerBounds, IReadOnlyList<double> UpperBounds) { int dimension = LowerBounds.Count; for (int i = 0; i < _parameters.NGrenade; i++) { PointND point = new PointND(0.0, dimension); for (int j = 0; j < dimension; j++) { point[j] = _uniformRand.URandVal(-1, 1); } _grenades.Add(new Agent(point, new PointND(0.0, 1))); } } private void FirstStep(IOOOptProblem Problem) { int dimension = Problem.LowerBounds.Count; _radiusExplosion = 2 * Math.Sqrt(dimension); InitAgents(Problem.LowerBounds, Problem.UpperBounds); EvalFunctionForGrenades(); } private void Init(GEMParams Parameters, IOOOptProblem Problem) { if (Problem == null) { throw new ArgumentNullException(nameof(Problem)); } if (!Parameters.IsParamsInit) { throw new ArgumentException("The parameters were created by the default constructor and have invalid values.\nYou need to create parameters with a custom constructor.", nameof(Parameters)); } _originalTargetFunction = Problem.TargetFunction; _lowerBounds = Problem.LowerBounds; _upperBounds = Problem.UpperBounds; _parameters = Parameters; _radiusGrenade = _parameters.InitRadiusGrenade; _radiusInitial = _parameters.InitRadiusGrenade; int dim = Problem.LowerBounds.Count; _mosd = 0; if (_grenades == null) { _grenades = new List<Agent>(_parameters.NGrenade); } else { _grenades.Capacity = _parameters.NGrenade; } if (_shrapnels == null) { InitShrapnels(); } else if (_shrapnels.Length != _parameters.NGrenade) { InitShrapnels(); } if (_tempArray == null) { _tempArray = new double[dim]; } else if (_tempArray.Length != dim) { _tempArray = new double[dim]; } if (_drnd == null) { _drnd = new PointND(0.0, dim); } else if (_drnd.Count != dim) { _drnd = new PointND(0.0, dim); } if (_dgrs == null) { _dgrs = new PointND(0, dim); } else if (_dgrs.Count != dim) { _dgrs = new PointND(0, dim); } if (_solution == null) { _solution = new Agent(dim, 1); } else if (_solution.Point.Count != dim) { _solution = new Agent(dim, 1); } } private void NextStep(IOOOptProblem Problem, int Iter) { ArrangeGrenades(); for (int j = 0; j < this._parameters.NGrenade; j++) { GenerateShrapneles(Problem, j, Iter); EvalFunctionForShrapnels(j); FindBestPosition(j); } UpdateParams(Iter, Problem.LowerBounds.Count); FindSolution(Problem); } private void InitShrapnels() { _shrapnels = new LinkedList<Agent>[_parameters.NGrenade]; for (int i = 0; i < _parameters.NGrenade; i++) { _shrapnels[i] = new LinkedList<Agent>(); } } /// <summary> /// The solution of the constrained optimization problem. /// </summary> public Agent Solution => _solution; /// <summary> /// Create object which uses custom implementation for random generators. /// </summary> public GEMOptimizer() : this(new ContUniformDist(), new NormalDist()) { } /// <summary> /// Create object which uses custom implementation for random generators. /// </summary> /// <param name="UniformGen"> Object, which implements <see cref="IContUniformGen"/> interface. </param> /// <param name="NormalGen"> Object, which implements <see cref="INormalGen"/> interface. </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="NormalGen"/> or <paramref name="UniformGen"/> is null. /// </exception> public GEMOptimizer(IContUniformGen UniformGen, INormalGen NormalGen) { if (UniformGen == null) { throw new ArgumentNullException(nameof(UniformGen)); } if (NormalGen == null) { throw new ArgumentNullException(nameof(NormalGen)); } _uniformRand = UniformGen; _normalRand = NormalGen; _targetFuncWithTransformedCoords = TargetFunctionWithTransformedCoords; } /// <summary> /// <see cref="IOOOptimizer{T}.Minimize(T, OOOptimizationProblem)"/> /// </summary> /// <param name="Parameters"> Parameters for method. </param> /// <param name="Problem"> An optimization problem. </param> /// <exception cref="InvalidOperationException"> If parameters do not set. </exception> /// <exception cref="ArgumentNullException"> If <paramref name="Problem"/> is null. </exception> /// <exception cref="ArithmeticException"> /// If the function has value is NaN, PositiveInfinity or NegativeInfinity. /// </exception> public void Minimize(GEMParams Parameters, IOOOptProblem Problem) { Init(Parameters, Problem); FirstStep(Problem); for (int i = 1; i <= _parameters.Imax; i++) { NextStep(Problem, i); } Clear(); } private void Clear() { _grenades.Clear(); for (int i = 0; i < _parameters.NGrenade; i++) { _shrapnels[i].Clear(); } } /// <summary> /// Update parameters. /// </summary> /// <param name="NumIter"></param> /// <param name="Dimension"></param> private void UpdateParams(int NumIter, int Dimension) { _radiusGrenade = _radiusInitial / Math.Pow(_parameters.RadiusReduct, (double)NumIter / _parameters.Imax); double m = _parameters.Mmax - (double)NumIter / _parameters.Imax * (_parameters.Mmax - _parameters.Mmin); _radiusExplosion = Math.Pow(2 * Math.Sqrt(Dimension), m) * Math.Pow(_radiusGrenade, 1 - m); _mosd = Math.Sin(Math.PI / 2 * Math.Pow(Math.Abs(NumIter - 0.1 * _parameters.Imax) / (0.9 * _parameters.Imax), _parameters.Psin)); } /// <summary> /// <see cref="IOOOptimizer{T}.Minimize(T, OOOptimizationProblem, CancellationToken)"/> /// </summary> /// <param name="Parameters"> Parameters for method. </param> /// <param name="Problem"> An optimization problem. </param> /// <param name="CancelToken"> <see cref="CancellationToken"/> </param> /// <exception cref="InvalidOperationException"> If parameters do not set. </exception> /// <exception cref="ArgumentNullException"> If <paramref name="Problem"/> is null. </exception> /// <exception cref="ArithmeticException"> /// If the function has value is NaN, PositiveInfinity or NegativeInfinity. /// </exception> /// <exception cref="OperationCanceledException"></exception> public void Minimize(GEMParams Parameters, IOOOptProblem Problem, CancellationToken CancelToken) { Init(Parameters, Problem); FirstStep(Problem); for (int i = 1; i <= _parameters.Imax; i++) { CancelToken.ThrowIfCancellationRequested(); NextStep(Problem, i); } Clear(); } /// <summary> /// <see cref="IOOOptimizer{T}.Minimize(T, OOOptimizationProblem, CancellationToken)"/> /// </summary> /// <param name="Parameters"> Parameters for method. </param> /// <param name="Problem"> An optimization problem. </param> /// <param name="Reporter"> /// Object which implement interface <see cref="IProgress{T}"/>, where T is /// <see cref="Progress"/>. <seealso cref="IOOOptimizer{T}.Minimize(T, OOOptimizationProblem, IProgress{Progress})"/> /// </param> /// <exception cref="InvalidOperationException"> If parameters do not set. </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="Problem"/> or <paramref name="Reporter"/> is null. /// </exception> /// <exception cref="ArithmeticException"> /// If the function has value is NaN, PositiveInfinity or NegativeInfinity. /// </exception> public void Minimize(GEMParams Parameters, IOOOptProblem Problem, IProgress<Progress> Reporter) { if (Reporter == null) { throw new ArgumentNullException(nameof(Reporter)); } Init(Parameters, Problem); FirstStep(Problem); Progress progress = new Progress(this, 1, _parameters.Imax, 1); Reporter.Report(progress); for (int i = 1; i <= _parameters.Imax; i++) { NextStep(Problem, i); progress.Current = i; Reporter.Report(progress); } Clear(); } /// <summary> /// <see cref="IOOOptimizer{T}.Minimize(T, OOOptimizationProblem, CancellationToken)"/> /// </summary> /// <param name="Parameters"> Parameters for method. </param> /// <param name="Problem"> An optimization problem. </param> /// <param name="Reporter"> /// Object which implement interface <see cref="IProgress{T}"/>, where T is /// <see cref="Progress"/>. <seealso cref="IOOOptimizer{T}.Minimize(T, OOOptimizationProblem, IProgress{Progress})"/> /// </param> /// <param name="CancelToken"> <see cref="CancellationToken"/> </param> /// <exception cref="InvalidOperationException"> If parameters do not set. </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="Problem"/> or <paramref name="Reporter"/> is null. /// </exception> /// <exception cref="ArithmeticException"> /// If the function has value is NaN, PositiveInfinity or NegativeInfinity. /// </exception> /// <exception cref="OperationCanceledException"></exception> public void Minimize(GEMParams Parameters, IOOOptProblem Problem, IProgress<Progress> Reporter, CancellationToken CancelToken) { if (Reporter == null) { throw new ArgumentNullException(nameof(Reporter)); } Init(Parameters, Problem); FirstStep(Problem); Progress progress = new Progress(this, 1, _parameters.Imax, 1); Reporter.Report(progress); for (int i = 1; i <= _parameters.Imax; i++) { CancelToken.ThrowIfCancellationRequested(); NextStep(Problem, i); progress.Current = i; Reporter.Report(progress); } Clear(); } } }
using System; using System.Collections.Concurrent; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading; using Orleans.Runtime; using Orleans.Concurrency; namespace Orleans.Serialization { using System.Runtime.CompilerServices; internal static class TypeUtilities { internal static bool IsOrleansPrimitive(this TypeInfo typeInfo) { var t = typeInfo.AsType(); return typeInfo.IsPrimitive || typeInfo.IsEnum || t == typeof(string) || t == typeof(DateTime) || t == typeof(Decimal) || (typeInfo.IsArray && typeInfo.GetElementType().GetTypeInfo().IsOrleansPrimitive()); } static readonly ConcurrentDictionary<Type, bool> shallowCopyableTypes = new ConcurrentDictionary<Type, bool>(); static readonly ConcurrentDictionary<Type, string> typeNameCache = new ConcurrentDictionary<Type, string>(); static readonly ConcurrentDictionary<Type, string> typeKeyStringCache = new ConcurrentDictionary<Type, string>(); static readonly ConcurrentDictionary<Type, byte[]> typeKeyCache = new ConcurrentDictionary<Type, byte[]>(); static TypeUtilities() { shallowCopyableTypes[typeof(Decimal)] = true; shallowCopyableTypes[typeof(DateTime)] = true; shallowCopyableTypes[typeof(TimeSpan)] = true; shallowCopyableTypes[typeof(IPAddress)] = true; shallowCopyableTypes[typeof(IPEndPoint)] = true; shallowCopyableTypes[typeof(SiloAddress)] = true; shallowCopyableTypes[typeof(GrainId)] = true; shallowCopyableTypes[typeof(ActivationId)] = true; shallowCopyableTypes[typeof(ActivationAddress)] = true; shallowCopyableTypes[typeof(CorrelationId)] = true; shallowCopyableTypes[typeof(string)] = true; shallowCopyableTypes[typeof(Immutable<>)] = true; shallowCopyableTypes[typeof(CancellationToken)] = true; } internal static bool IsOrleansShallowCopyable(this Type t) { bool result; if (shallowCopyableTypes.TryGetValue(t, out result)) { return result; } var typeInfo = t.GetTypeInfo(); if (typeInfo.IsPrimitive || typeInfo.IsEnum) { shallowCopyableTypes[t] = true; return true; } if (typeInfo.GetCustomAttributes(typeof(ImmutableAttribute), false).Any()) { shallowCopyableTypes[t] = true; return true; } if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Immutable<>)) { shallowCopyableTypes[t] = true; return true; } if (typeInfo.IsValueType && !typeInfo.IsGenericType && !typeInfo.IsGenericTypeDefinition) { result = typeInfo.GetFields().All(f => !(f.FieldType == t) && IsOrleansShallowCopyable(f.FieldType)); shallowCopyableTypes[t] = result; return result; } shallowCopyableTypes[t] = false; return false; } internal static bool IsSpecializationOf(this Type t, Type match) { var typeInfo = t.GetTypeInfo(); return typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == match; } internal static string OrleansTypeName(this Type t) { string name; if (typeNameCache.TryGetValue(t, out name)) return name; name = TypeUtils.GetTemplatedName(t, _ => !_.IsGenericParameter); typeNameCache[t] = name; return name; } public static byte[] OrleansTypeKey(this Type t) { byte[] key; if (typeKeyCache.TryGetValue(t, out key)) return key; key = Encoding.UTF8.GetBytes(t.OrleansTypeKeyString()); typeKeyCache[t] = key; return key; } public static string OrleansTypeKeyString(this Type t) { string key; if (typeKeyStringCache.TryGetValue(t, out key)) return key; var typeInfo = t.GetTypeInfo(); var sb = new StringBuilder(); if (typeInfo.IsGenericTypeDefinition) { sb.Append(GetBaseTypeKey(t)); sb.Append('\''); sb.Append(typeInfo.GetGenericArguments().Length); } else if (typeInfo.IsGenericType) { sb.Append(GetBaseTypeKey(t)); sb.Append('<'); var first = true; foreach (var genericArgument in t.GetGenericArguments()) { if (!first) { sb.Append(','); } first = false; sb.Append(OrleansTypeKeyString(genericArgument)); } sb.Append('>'); } else if (t.IsArray) { sb.Append(OrleansTypeKeyString(t.GetElementType())); sb.Append('['); if (t.GetArrayRank() > 1) { sb.Append(',', t.GetArrayRank() - 1); } sb.Append(']'); } else { sb.Append(GetBaseTypeKey(t)); } key = sb.ToString(); typeKeyStringCache[t] = key; return key; } private static string GetBaseTypeKey(Type t) { var typeInfo = t.GetTypeInfo(); string namespacePrefix = ""; if ((typeInfo.Namespace != null) && !typeInfo.Namespace.StartsWith("System.") && !typeInfo.Namespace.Equals("System")) { namespacePrefix = typeInfo.Namespace + '.'; } if (typeInfo.IsNestedPublic) { return namespacePrefix + OrleansTypeKeyString(typeInfo.DeclaringType) + "." + typeInfo.Name; } return namespacePrefix + typeInfo.Name; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public static string GetLocationSafe(this Assembly a) { if (a.IsDynamic) { return "dynamic"; } try { return a.Location; } catch (Exception) { return "unknown"; } } public static bool IsTypeIsInaccessibleForSerialization(Type type, Module fromModule, Assembly fromAssembly) { var typeInfo = type.GetTypeInfo(); if (typeInfo.IsGenericTypeDefinition) { // Guard against invalid type constraints, which appear when generating code for some languages. foreach (var parameter in typeInfo.GenericTypeParameters) { if (parameter.GetTypeInfo().GetGenericParameterConstraints().Any(IsSpecialClass)) { return true; } } } if (!typeInfo.IsVisible && type.IsConstructedGenericType) { foreach (var inner in typeInfo.GetGenericArguments()) { if (IsTypeIsInaccessibleForSerialization(inner, fromModule, fromAssembly)) { return true; } } if (IsTypeIsInaccessibleForSerialization(typeInfo.GetGenericTypeDefinition(), fromModule, fromAssembly)) { return true; } } if ((typeInfo.IsNotPublic || !typeInfo.IsVisible) && !AreInternalsVisibleTo(typeInfo.Assembly, fromAssembly)) { // subtype is defined in a different assembly from the outer type if (!typeInfo.Module.Equals(fromModule)) { return true; } // subtype defined in a different assembly from the one we are generating serializers for. if (!typeInfo.Assembly.Equals(fromAssembly)) { return true; } } // For arrays, check the element type. if (typeInfo.IsArray) { if (IsTypeIsInaccessibleForSerialization(typeInfo.GetElementType(), fromModule, fromAssembly)) { return true; } } // For nested types, check that the declaring type is accessible. if (typeInfo.IsNested) { if (IsTypeIsInaccessibleForSerialization(typeInfo.DeclaringType, fromModule, fromAssembly)) { return true; } } return typeInfo.IsNestedPrivate || typeInfo.IsNestedFamily || type.IsPointer; } /// <summary> /// Returns true if <paramref name="fromAssembly"/> has exposed its internals to <paramref name="toAssembly"/>, false otherwise. /// </summary> /// <param name="fromAssembly">The assembly containing internal types.</param> /// <param name="toAssembly">The assembly requiring access to internal types.</param> /// <returns> /// true if <paramref name="fromAssembly"/> has exposed its internals to <paramref name="toAssembly"/>, false otherwise /// </returns> private static bool AreInternalsVisibleTo(Assembly fromAssembly, Assembly toAssembly) { // If the to-assembly is null, it cannot have internals visible to it. if (toAssembly == null) { return false; } // Check InternalsVisibleTo attributes on the from-assembly, pointing to the to-assembly. var serializationAssemblyName = toAssembly.GetName().FullName; var internalsVisibleTo = fromAssembly.GetCustomAttributes<InternalsVisibleToAttribute>(); return internalsVisibleTo.Any(_ => _.AssemblyName == serializationAssemblyName); } private static bool IsSpecialClass(Type type) { return type == typeof(object) || type == typeof(Array) || type == typeof(Delegate) || type == typeof(Enum) || type == typeof(ValueType); } } }
using System.Collections.Specialized; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OAuth2.Configuration; using OAuth2.Infrastructure; using OAuth2.Models; using RestSharp; using RestSharp.Contrib; namespace OAuth2.Client { /// <summary> /// Base class for OAuth2 client implementation. /// </summary> public abstract class OAuth2Client : IClient { private const string AccessTokenKey = "access_token"; private readonly IRequestFactory _factory; /// <summary> /// Client configuration object. /// </summary> public IClientConfiguration Configuration { get; private set; } /// <summary> /// Friendly name of provider (OAuth2 service). /// </summary> public abstract string Name { get; } /// <summary> /// State (any additional information that was provided by application and is posted back by service). /// </summary> public string State { get; private set; } /// <summary> /// Access token returned by provider. Can be used for further calls of provider API. /// </summary> public virtual string AccessToken { get; protected set; } /// <summary> /// Initializes a new instance of the <see cref="OAuth2Client"/> class. /// </summary> /// <param name="factory">The factory.</param> /// <param name="configuration">The configuration.</param> protected OAuth2Client(IRequestFactory factory, IClientConfiguration configuration) { _factory = factory; Configuration = configuration; } /// <summary> /// Returns URI of service which should be called in order to start authentication process. /// This URI should be used for rendering login link. /// </summary> /// <param name="state"> /// Any additional information that will be posted back by service. /// </param> public virtual string GetLoginLinkUri(string state = null) { var client = _factory.CreateClient(AccessCodeServiceEndpoint); var request = _factory.CreateRequest(AccessCodeServiceEndpoint); request.AddObject(new { response_type = "code", client_id = Configuration.ClientId, redirect_uri = Configuration.RedirectUri, scope = Configuration.Scope, state }); return client.BuildUri(request).ToString(); } /// <summary> /// Obtains user information using OAuth2 service and data provided via callback request. /// </summary> /// <param name="parameters">Callback request payload (parameters).</param> public UserInfo GetUserInfo(NameValueCollection parameters) { CheckErrorAndSetState(parameters); QueryAccessToken(parameters); return GetUserInfo(); } /// <summary> /// Issues query for access token and returns access token. /// </summary> /// <param name="parameters">Callback request payload (parameters).</param> public string GetToken(NameValueCollection parameters) { CheckErrorAndSetState(parameters); QueryAccessToken(parameters); return AccessToken; } /// <summary> /// Defines URI of service which issues access code. /// </summary> protected abstract Endpoint AccessCodeServiceEndpoint { get; } /// <summary> /// Defines URI of service which issues access token. /// </summary> protected abstract Endpoint AccessTokenServiceEndpoint { get; } /// <summary> /// Defines URI of service which allows to obtain information about user /// who is currently logged in. /// </summary> protected abstract Endpoint UserInfoServiceEndpoint { get; } private void CheckErrorAndSetState(NameValueCollection parameters) { const string errorFieldName = "error"; var error = parameters[errorFieldName]; if (!error.IsEmpty()) { throw new UnexpectedResponseException(errorFieldName); } State = parameters["state"]; } /// <summary> /// Issues query for access token and parses response. /// </summary> /// <param name="parameters">Callback request payload (parameters).</param> private void QueryAccessToken(NameValueCollection parameters) { var client = _factory.CreateClient(AccessTokenServiceEndpoint); var request = _factory.CreateRequest(AccessTokenServiceEndpoint, Method.POST); BeforeGetAccessToken(new BeforeAfterRequestArgs { Client = client, Request = request, Parameters = parameters, Configuration = Configuration }); var response = client.ExecuteAndVerify(request); AfterGetAccessToken(new BeforeAfterRequestArgs { Response = response, Parameters = parameters }); AccessToken = ParseAccessTokenResponse(response.Content); } protected virtual string ParseAccessTokenResponse(string content) { try { // response can be sent in JSON format var token = (string)JObject.Parse(content).SelectToken(AccessTokenKey); if (token.IsEmpty()) { throw new UnexpectedResponseException(AccessTokenKey); } return token; } catch (JsonReaderException) { // or it can be in "query string" format (param1=val1&param2=val2) var collection = HttpUtility.ParseQueryString(content); return collection.GetOrThrowUnexpectedResponse(AccessTokenKey); } } /// <summary> /// Should return parsed <see cref="UserInfo"/> using content received from provider. /// </summary> /// <param name="content">The content which is received from provider.</param> protected abstract UserInfo ParseUserInfo(string content); protected virtual void BeforeGetAccessToken(BeforeAfterRequestArgs args) { args.Request.AddObject(new { code = args.Parameters.GetOrThrowUnexpectedResponse("code"), client_id = Configuration.ClientId, client_secret = Configuration.ClientSecret, redirect_uri = Configuration.RedirectUri, grant_type = "authorization_code" }); } /// <summary> /// Called just after obtaining response with access token from service. /// Allows to read extra data returned along with access token. /// </summary> protected virtual void AfterGetAccessToken(BeforeAfterRequestArgs args) { } /// <summary> /// Called just before issuing request to service when everything is ready. /// Allows to add extra parameters to request or do any other needed preparations. /// </summary> protected virtual void BeforeGetUserInfo(BeforeAfterRequestArgs args) { } /// <summary> /// Obtains user information using provider API. /// </summary> private UserInfo GetUserInfo() { var client = _factory.CreateClient(UserInfoServiceEndpoint); client.Authenticator = new OAuth2UriQueryParameterAuthenticator(AccessToken); var request = _factory.CreateRequest(UserInfoServiceEndpoint); BeforeGetUserInfo(new BeforeAfterRequestArgs { Client = client, Request = request, Configuration = Configuration }); var response = client.ExecuteAndVerify(request); var result = ParseUserInfo(response.Content); result.ProviderName = Name; return result; } } }
using System; using System.Diagnostics; using System.IO; using System.Collections.Generic; using System.Linq; using DevTyr.Gullap.IO; using DevTyr.Gullap.Model; using DevTyr.Gullap.Parser; using DevTyr.Gullap.Parser.Markdown; using DevTyr.Gullap.Templating; using DevTyr.Gullap.Templating.Nustache; using DevTyr.Gullap.Extensions; namespace DevTyr.Gullap { public class Converter { private ConverterOptions Options { get; set; } private SitePaths Paths { get; set; } private IParser internalParser = new MarkdownParser(); private ITemplater internalTemplater = new NustacheTemplater(); public Converter (ConverterOptions options) { Guard.NotNull(options, "options"); Guard.NotNullOrEmpty(options.SitePath, "options.SitePath"); Options = options; Paths = new SitePaths(options.SitePath); } public void SetParser (IParser parser) { if (parser == null) throw new ArgumentNullException("parser"); internalParser = parser; } public void SetTemplater (ITemplater templater) { if (templater == null) throw new ArgumentNullException("templater"); internalTemplater = templater; } public void InitializeSite () { var generator = new SiteGenerator(); generator.Generate(new SitePaths(Options.SitePath)); } public void ConvertAll () { CleanOutput(); CopyAssets(); ConvertAllInternal(); } public void ConvertSingleFile(string fileName) { var workspaceInfo = new WorkspaceInfo(Paths); var workspaceFiles = workspaceInfo.GetContent(fileName); var fileContentToParse = workspaceFiles.FilesToParse.FirstOrDefault(item => item.FileName.Contains(fileName)); if (fileContentToParse == null) { Trace.TraceError("Could not find contents for file {0}", fileName); return; } var contentsToParse = new List<MetaContent> {fileContentToParse}; FillCategoryPages(contentsToParse); Trace.TraceInformation("Parsing contents for {0} files", contentsToParse.Count); ParseContents(contentsToParse); Trace.TraceInformation("Generating template data"); Trace.TraceInformation("Found {0} pages", contentsToParse.Count); foreach (var content in contentsToParse) { dynamic metadata = content.Page != null ? ParseTemplateData(contentsToParse, content.Page) : ParseTemplateData(contentsToParse, content.Post); Export(content, metadata); Trace.TraceInformation("Exported {0}", content.FileName); } } private void CleanOutput () { var files = Directory.GetFiles(Paths.OutputPath, "*.*", SearchOption.AllDirectories); foreach(var file in files) File.Delete(file); } private void CopyAssets () { DirectoryExtensions.DirectoryCopy(Paths.AssetsPath, Paths.OutputPath, true); } private void ConvertAllInternal () { var workspaceInfo = new WorkspaceInfo(Paths); var workspaceFiles = workspaceInfo.GetContents(); var contentsToParse = workspaceFiles.FilesToParse; FillCategoryPages(contentsToParse); Trace.TraceInformation("Parsing contents for {0} files", contentsToParse.Count); ParseContents(contentsToParse); Trace.TraceInformation("Generating template data"); Trace.TraceInformation("Found {0} pages", contentsToParse.Count); foreach (var content in contentsToParse) { dynamic metadata = content.Page != null ? ParseTemplateData(contentsToParse, content.Page) : ParseTemplateData(contentsToParse, content.Post); Export (content, metadata); Trace.TraceInformation("Exported {0}", content.FileName); } foreach (var file in workspaceFiles.FilesNotToParse) { Copy(file); } } private void FillCategoryPages(List<MetaContent> metaContents) { foreach (var content in metaContents) { if (content.Post != null && !string.IsNullOrWhiteSpace(content.Post.Category)) { content.Post.CategoryPosts = metaContents.Where(item => item.Post != null && !string.IsNullOrWhiteSpace(item.Post.Category) && item.Post.Category == content.Post.Category) .Select(item => item.Post) .ToList(); } if (content.Page != null && !string.IsNullOrWhiteSpace(content.Page.Category)) { content.Page.CategoryPages = metaContents.Where(item => item.Page != null && !string.IsNullOrWhiteSpace(item.Page.Category) && item.Page.Category == content.Page.Category) .Select(item => item.Page) .ToList(); } } } private dynamic ParseTemplateData(List<MetaContent> metaContents, ContentBase currentContent) { dynamic metadata = new { site = new { config = Options.SiteConfiguration, time = DateTime.Now, pages = metaContents.Where(content => content.Page != null && !content.Page.Draft).Select(content => content.Page).ToArray(), posts = metaContents.Where(content => content.Post != null && !content.Post.Draft).Select(content => content.Post).OrderByDescending(post => post.Date).ToArray(), pageCategories = metaContents.Where(content => content.Page != null && !string.IsNullOrWhiteSpace(content.Page.Category)).Select(t => new { t.Page.Category, t.Page }).ToDictionary(arg => arg, arg => arg), postCategories = metaContents.Where(content => content.Post != null && !string.IsNullOrWhiteSpace(content.Post.Category)).Select(t => new { t.Post.Category, t.Post}).ToDictionary(arg => arg, arg => arg) }, current = currentContent }; return metadata; } private void ParseContents(IEnumerable<MetaContent> metaContents) { foreach (var content in metaContents) { Trace.TraceInformation("Parsing content for " + content.FileName); if (content.Page != null) { content.Page.Content = internalParser.Parse(content.Page.Content); } if (content.Post != null) { content.Post.Content = internalParser.Parse(content.Post.Content); } } } private void Export (MetaContent metaContent, dynamic metadata) { var targetPath = metaContent.GetTargetFileName(Paths); if (!metaContent.HasValidTemplate()) { Trace.TraceWarning("No template given for file {0}", metaContent.FileName); return; } FileSystem.EnsureDirectory(targetPath); var result = internalTemplater.Transform (Paths.TemplatePath, metaContent.GetTemplate(), metadata); File.WriteAllText (targetPath, result); } private void Copy(string file) { var targetDirectory = Path.GetDirectoryName(file.Replace(Paths.PagesPath, Paths.OutputPath).Replace(Paths.PostsPath, Paths.OutputPath)); if (string.IsNullOrWhiteSpace(targetDirectory)) { Trace.TraceWarning("Unable to evalaute target directory for {0}", file); return; } FileSystem.EnsureDirectory(targetDirectory); var targetFileName = Path.GetFileName(file); File.Copy(file, Path.Combine(targetDirectory, targetFileName)); } } }
using System; using System.Collections; using System.Text; /* * Copyright 2007 ZXing 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. */ namespace com.google.zxing.common { /// <summary> /// <p>Represents a 2D matrix of bits. In function arguments below, and throughout the common /// module, x is the column position, and y is the row position. The ordering is always x, y. /// The origin is at the top-left.</p> /// /// <p>Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins /// with a new int. This is done intentionally so that we can copy out a row into a BitArray very /// efficiently.</p> /// /// <p>The ordering of bits is row-major. Within each int, the least significant bits are used first, /// meaning they represent lower x values. This is compatible with BitArray's implementation.</p> /// /// @author Sean Owen /// @author dswitkin@google.com (Daniel Switkin) /// </summary> public sealed class BitMatrix { private readonly int width; private readonly int height; private readonly int rowSize; private readonly int[] bits; // A helper to construct a square matrix. public BitMatrix(int dimension) : this(dimension, dimension) { } public BitMatrix(int width, int height) { if (width < 1 || height < 1) { throw new System.ArgumentException("Both dimensions must be greater than 0"); } this.width = width; this.height = height; this.rowSize = (width + 31) >> 5; bits = new int[rowSize * height]; } /// <summary> /// <p>Gets the requested bit, where true means black.</p> /// </summary> /// <param name="x"> The horizontal component (i.e. which column) </param> /// <param name="y"> The vertical component (i.e. which row) </param> /// <returns> value of given bit in matrix </returns> public bool get(int x, int y) { int offset = y * rowSize + (x >> 5); return (((int)((uint)bits[offset] >> (x & 0x1f))) & 1) != 0; } /// <summary> /// <p>Sets the given bit to true.</p> /// </summary> /// <param name="x"> The horizontal component (i.e. which column) </param> /// <param name="y"> The vertical component (i.e. which row) </param> public void set(int x, int y) { int offset = y * rowSize + (x >> 5); bits[offset] |= 1 << (x & 0x1f); } /// <summary> /// <p>Flips the given bit.</p> /// </summary> /// <param name="x"> The horizontal component (i.e. which column) </param> /// <param name="y"> The vertical component (i.e. which row) </param> public void flip(int x, int y) { int offset = y * rowSize + (x >> 5); bits[offset] ^= 1 << (x & 0x1f); } /// <summary> /// Clears all bits (sets to false). /// </summary> public void clear() { int max = bits.Length; for (int i = 0; i < max; i++) { bits[i] = 0; } } /// <summary> /// <p>Sets a square region of the bit matrix to true.</p> /// </summary> /// <param name="left"> The horizontal position to begin at (inclusive) </param> /// <param name="top"> The vertical position to begin at (inclusive) </param> /// <param name="width"> The width of the region </param> /// <param name="height"> The height of the region </param> public void setRegion(int left, int top, int width, int height) { if (top < 0 || left < 0) { throw new System.ArgumentException("Left and top must be nonnegative"); } if (height < 1 || width < 1) { throw new System.ArgumentException("Height and width must be at least 1"); } int right = left + width; int bottom = top + height; if (bottom > this.height || right > this.width) { throw new System.ArgumentException("The region must fit inside the matrix"); } for (int y = top; y < bottom; y++) { int offset = y * rowSize; for (int x = left; x < right; x++) { bits[offset + (x >> 5)] |= 1 << (x & 0x1f); } } } /// <summary> /// A fast method to retrieve one row of data from the matrix as a BitArray. /// </summary> /// <param name="y"> The row to retrieve </param> /// <param name="row"> An optional caller-allocated BitArray, will be allocated if null or too small </param> /// <returns> The resulting BitArray - this reference should always be used even when passing /// your own row </returns> public BitArray getRow(int y, BitArray row) { if (row == null || row.Size < width) { row = new BitArray(width); } int offset = y * rowSize; for (int x = 0; x < rowSize; x++) { row.setBulk(x << 5, bits[offset + x]); } return row; } /// <param name="y"> row to set </param> /// <param name="row"> <seealso cref="BitArray"/> to copy from </param> public void setRow(int y, BitArray row) { Array.Copy(row.BitArrayBits, 0, bits, y * rowSize, rowSize); } /// <summary> /// This is useful in detecting the enclosing rectangle of a 'pure' barcode. /// </summary> /// <returns> {left,top,width,height} enclosing rectangle of all 1 bits, or null if it is all white </returns> public int[] EnclosingRectangle { get { int left = this.width; int top = this.height; int right = -1; int bottom = -1; for (int y = 0; y < this.height; y++) { for (int x32 = 0; x32 < rowSize; x32++) { int theBits = bits[y * rowSize + x32]; if (theBits != 0) { if (y < top) { top = y; } if (y > bottom) { bottom = y; } if (x32 * 32 < left) { int bit = 0; while ((theBits << (31 - bit)) == 0) { bit++; } if ((x32 * 32 + bit) < left) { left = x32 * 32 + bit; } } if (x32 * 32 + 31 > right) { int bit = 31; while (((int)((uint)theBits >> bit)) == 0) { bit--; } if ((x32 * 32 + bit) > right) { right = x32 * 32 + bit; } } } } } int width = right - left; int height = bottom - top; if (width < 0 || height < 0) { return null; } return new int[] {left, top, width, height}; } } /// <summary> /// This is useful in detecting a corner of a 'pure' barcode. /// </summary> /// <returns> {x,y} coordinate of top-left-most 1 bit, or null if it is all white </returns> public int[] TopLeftOnBit { get { int bitsOffset = 0; while (bitsOffset < bits.Length && bits[bitsOffset] == 0) { bitsOffset++; } if (bitsOffset == bits.Length) { return null; } int y = bitsOffset / rowSize; int x = (bitsOffset % rowSize) << 5; int theBits = bits[bitsOffset]; int bit = 0; while ((theBits << (31 - bit)) == 0) { bit++; } x += bit; return new int[] {x, y}; } } public int[] BottomRightOnBit { get { int bitsOffset = bits.Length - 1; while (bitsOffset >= 0 && bits[bitsOffset] == 0) { bitsOffset--; } if (bitsOffset < 0) { return null; } int y = bitsOffset / rowSize; int x = (bitsOffset % rowSize) << 5; int theBits = bits[bitsOffset]; int bit = 31; while (((int)((uint)theBits >> bit)) == 0) { bit--; } x += bit; return new int[] {x, y}; } } /// <returns> The width of the matrix </returns> public int Width { get { return width; } } /// <returns> The height of the matrix </returns> public int Height { get { return height; } } public override bool Equals(object o) { if (!(o is BitMatrix)) { return false; } BitMatrix other = (BitMatrix) o; if (width != other.width || height != other.height || rowSize != other.rowSize || bits.Length != other.bits.Length) { return false; } for (int i = 0; i < bits.Length; i++) { if (bits[i] != other.bits[i]) { return false; } } return true; } public override int GetHashCode() { int hash = width; hash = 31 * hash + width; hash = 31 * hash + height; hash = 31 * hash + rowSize; foreach (int bit in bits) { hash = 31 * hash + bit; } return hash; } public override string ToString() { StringBuilder result = new StringBuilder(height * (width + 1)); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { result.Append(get(x, y) ? "X " : " "); } result.Append('\n'); } return result.ToString(); } } }
/* * clsUDP * shall start a listner, and raise an event every time data arrives on a port * shall also be able to send data via udp protocol * .Dispose shall remove all resources associated with the class */ using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace HASystem.Server.DHCP { public class UDPAsync { #region fields private Int32 portToListen = 0; private Int32 portToSend = 0; private IPAddress endpointIp; private bool isListening; // callbacks for send/receive private UDPState callback; #endregion fields #region events public delegate void DataReceivedEventHandler(byte[] data, IPEndPoint endPoint); public event DataReceivedEventHandler dataReceived; public delegate void ErrorEventHandler(string message); #endregion events #region ctor public UDPAsync() { isListening = false; } public UDPAsync(Int32 portToListen, Int32 portToSend, IPAddress endpointIp) { try { isListening = false; this.portToListen = portToListen; this.portToSend = portToSend; this.endpointIp = endpointIp; StartListener(); } catch (Exception) { // TODO: handle exception // Console.WriteLine(ex.Message); } } ~UDPAsync() { try { StopListener(); if (callback.Client != null) { callback.Client.Close(); } callback.Client = null; callback.EndPoint = null; } catch (Exception) { // TODO: handle exception //Console.WriteLine(ex.Message); } } #endregion ctor #region public methods public void SendData(byte[] data) { //function to send data as a byte stream to a remote socket // modified to work as a callback rather than a block try { callback.Client.BeginSend(data, data.Length, "255.255.255.255", portToSend, new AsyncCallback(OnDataSent), callback); } catch (Exception) { // TODO: handle exception // Console.WriteLine(ex.Message); } } public void StopListener() { //stop the listener thread try { isListening = false; if (callback.Client != null) { callback.Client.Close(); } callback.Client = null; callback.EndPoint = null; } catch (Exception) { // TODO: handle exception //Console.WriteLine(ex.Message); } } #endregion public methods #region private methods private void OnDataSent(IAsyncResult asyn) { // This is the call back function, which will be invoked when a client is connected try { //get the data UdpClient client = ((UDPState)asyn.AsyncState).Client; // stop the send call back client.EndSend(asyn); } catch (Exception) { if (isListening == true) { // TODO: handle exception //Console.WriteLine(ex.Message); } } } private void InitializeListnerCallBack() { //function to start the listener call back everytime something is recieved try { // start receive callback callback.Client.BeginReceive(new AsyncCallback(OnDataReceived), callback); } catch (Exception) { if (isListening == true) { // TODO: handle exception //Console.WriteLine(ex.Message); } } } private void OnDataReceived(IAsyncResult asyn) { // This is the call back function, which will be invoked when a client is connected Byte[] receiveBytes; UdpClient client; IPEndPoint endPoint; try { client = (UdpClient)((UDPState)(asyn.AsyncState)).Client; endPoint = (IPEndPoint)((UDPState)(asyn.AsyncState)).EndPoint; receiveBytes = client.EndReceive(asyn, ref endPoint); //raise the event with the data received dataReceived(receiveBytes, endPoint); } catch (Exception) { if (isListening == true) { // TODO: handle exception //Console.WriteLine(ex.Message); } } finally { client = null; endPoint = null; receiveBytes = null; // recall the call back InitializeListnerCallBack(); } } private void StartListener() { //function to start the listener //if the the listner is active, destroy it and restart // shall mark the flag that the listner is active IPEndPoint ipLocalEndPoint; try { isListening = false; //get the ipEndPoint ipLocalEndPoint = new IPEndPoint(endpointIp, portToListen); // if the udpclient interface is active destroy if (callback.Client != null) { callback.Client.Close(); } callback.Client = null; callback.EndPoint = null; //re initialise the udp client callback = new UDPState(); callback.EndPoint = ipLocalEndPoint; callback.Client = new UdpClient(ipLocalEndPoint); isListening = true; // wait for data InitializeListnerCallBack(); } catch (Exception) { if (isListening == true) { // TODO: handle exception //Console.WriteLine(ex.Message); } } finally { if (callback.Client == null) { Thread.Sleep(1000); StartListener(); } else { ipLocalEndPoint = null; } } } #endregion private methods } }
// ----------------------------------------------------------------------- // Licensed to The .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ----------------------------------------------------------------------- using System.Diagnostics; using System.Numerics; namespace System.Security.Cryptography.Asn1 { internal sealed partial class AsnWriter { /// <summary> /// Write an Integer value with tag UNIVERSAL 2. /// </summary> /// <param name="value">The value to write.</param> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteInteger(long value) { this.WriteIntegerCore(Asn1Tag.Integer, value); } /// <summary> /// Write an Integer value with tag UNIVERSAL 2. /// </summary> /// <param name="value">The value to write.</param> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteInteger(ulong value) { this.WriteNonNegativeIntegerCore(Asn1Tag.Integer, value); } /// <summary> /// Write an Integer value with tag UNIVERSAL 2. /// </summary> /// <param name="value">The value to write.</param> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteInteger(BigInteger value) { this.WriteIntegerCore(Asn1Tag.Integer, value); } /// <summary> /// Write an Integer value with a specified tag. /// </summary> /// <param name="value">The integer value to write, in signed big-endian byte order.</param> /// <exception cref="CryptographicException"> /// the 9 most sigificant bits are all set --OR-- /// the 9 most sigificant bits are all unset /// </exception> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteInteger(ReadOnlySpan<byte> value) { this.WriteIntegerCore(Asn1Tag.Integer, value); } /// <summary> /// Write an Integer value with a specified tag. /// </summary> /// <param name="tag">The tag to write.</param> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentException"> /// <paramref name="tag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="tag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteInteger(Asn1Tag tag, long value) { CheckUniversalTag(tag, UniversalTagNumber.Integer); this.WriteIntegerCore(tag.AsPrimitive(), value); } /// <summary> /// Write an Integer value with a specified tag. /// </summary> /// <param name="tag">The tag to write.</param> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentException"> /// <paramref name="tag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="tag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteInteger(Asn1Tag tag, ulong value) { CheckUniversalTag(tag, UniversalTagNumber.Integer); this.WriteNonNegativeIntegerCore(tag.AsPrimitive(), value); } /// <summary> /// Write an Integer value with a specified tag. /// </summary> /// <param name="tag">The tag to write.</param> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentException"> /// <paramref name="tag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="tag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteInteger(Asn1Tag tag, BigInteger value) { CheckUniversalTag(tag, UniversalTagNumber.Integer); this.WriteIntegerCore(tag.AsPrimitive(), value); } /// <summary> /// Write an Integer value with a specified tag. /// </summary> /// <param name="tag">The tag to write.</param> /// <param name="value">The integer value to write, in signed big-endian byte order.</param> /// <exception cref="ArgumentException"> /// <paramref name="tag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="tag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> /// <exception cref="CryptographicException"> /// the 9 most sigificant bits are all set --OR-- /// the 9 most sigificant bits are all unset /// </exception> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteInteger(Asn1Tag tag, ReadOnlySpan<byte> value) { CheckUniversalTag(tag, UniversalTagNumber.Integer); this.WriteIntegerCore(tag.AsPrimitive(), value); } /// <summary> /// Write an Integer value with tag UNIVERSAL 2. /// </summary> /// <param name="value">The integer value to write, in unsigned big-endian byte order.</param> /// <exception cref="CryptographicException"> /// the 9 most sigificant bits are all unset /// </exception> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteIntegerUnsigned(ReadOnlySpan<byte> value) { this.WriteIntegerUnsignedCore(Asn1Tag.Integer, value); } /// <summary> /// Write an Integer value with a specified tag. /// </summary> /// <param name="tag">The tag to write.</param> /// <param name="value">The integer value to write, in unsigned big-endian byte order.</param> /// <exception cref="ArgumentException"> /// <paramref name="tag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="tag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> /// <exception cref="CryptographicException"> /// the 9 most sigificant bits are all unset /// </exception> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteIntegerUnsigned(Asn1Tag tag, ReadOnlySpan<byte> value) { CheckUniversalTag(tag, UniversalTagNumber.Integer); this.WriteIntegerUnsignedCore(tag.AsPrimitive(), value); } // T-REC-X.690-201508 sec 8.3 private void WriteIntegerCore(Asn1Tag tag, long value) { if (value >= 0) { this.WriteNonNegativeIntegerCore(tag, (ulong)value); return; } int valueLength; if (value >= sbyte.MinValue) { valueLength = 1; } else if (value >= short.MinValue) { valueLength = 2; } else if (value >= unchecked((long)0xFFFFFFFF_FF800000)) { valueLength = 3; } else if (value >= int.MinValue) { valueLength = 4; } else if (value >= unchecked((long)0xFFFFFF80_00000000)) { valueLength = 5; } else if (value >= unchecked((long)0xFFFF8000_00000000)) { valueLength = 6; } else if (value >= unchecked((long)0xFF800000_00000000)) { valueLength = 7; } else { valueLength = 8; } Debug.Assert(!tag.IsConstructed); this.WriteTag(tag); this.WriteLength(valueLength); long remaining = value; int idx = this._offset + valueLength - 1; do { this._buffer[idx] = (byte)remaining; remaining >>= 8; idx--; } while (idx >= this._offset); #if DEBUG if (valueLength > 1) { // T-REC-X.690-201508 sec 8.3.2 // Cannot start with 9 bits of 1 (or 9 bits of 0, but that's not this method). Debug.Assert(this._buffer[this._offset] != 0xFF || this._buffer[this._offset + 1] < 0x80); } #endif this._offset += valueLength; } // T-REC-X.690-201508 sec 8.3 private void WriteNonNegativeIntegerCore(Asn1Tag tag, ulong value) { int valueLength; // 0x80 needs two bytes: 0x00 0x80 if (value < 0x80) { valueLength = 1; } else if (value < 0x8000) { valueLength = 2; } else if (value < 0x800000) { valueLength = 3; } else if (value < 0x80000000) { valueLength = 4; } else if (value < 0x80_00000000) { valueLength = 5; } else if (value < 0x8000_00000000) { valueLength = 6; } else if (value < 0x800000_00000000) { valueLength = 7; } else if (value < 0x80000000_00000000) { valueLength = 8; } else { valueLength = 9; } // Clear the constructed bit, if it was set. Debug.Assert(!tag.IsConstructed); this.WriteTag(tag); this.WriteLength(valueLength); ulong remaining = value; int idx = this._offset + valueLength - 1; do { this._buffer[idx] = (byte)remaining; remaining >>= 8; idx--; } while (idx >= this._offset); #if DEBUG if (valueLength > 1) { // T-REC-X.690-201508 sec 8.3.2 // Cannot start with 9 bits of 0 (or 9 bits of 1, but that's not this method). Debug.Assert(this._buffer[this._offset] != 0 || this._buffer[this._offset + 1] > 0x7F); } #endif this._offset += valueLength; } private void WriteIntegerUnsignedCore(Asn1Tag tag, ReadOnlySpan<byte> value) { if (value.IsEmpty) { throw new CryptographicException(SR.Resource("Cryptography_Der_Invalid_Encoding")); } // T-REC-X.690-201508 sec 8.3.2 if (value.Length > 1 && value[0] == 0 && value[1] < 0x80) { throw new CryptographicException(SR.Resource("Cryptography_Der_Invalid_Encoding")); } Debug.Assert(!tag.IsConstructed); this.WriteTag(tag); if (value[0] >= 0x80) { this.WriteLength(checked(value.Length + 1)); this._buffer[this._offset] = 0; this._offset++; } else { this.WriteLength(value.Length); } value.CopyTo(this._buffer.AsSpan(this._offset)); this._offset += value.Length; } private void WriteIntegerCore(Asn1Tag tag, ReadOnlySpan<byte> value) { this.CheckDisposed(); if (value.IsEmpty) { throw new CryptographicException(SR.Resource("Cryptography_Der_Invalid_Encoding")); } // T-REC-X.690-201508 sec 8.3.2 if (value.Length > 1) { ushort bigEndianValue = (ushort)(value[0] << 8 | value[1]); const ushort RedundancyMask = 0b1111_1111_1000_0000; ushort masked = (ushort)(bigEndianValue & RedundancyMask); // If the first 9 bits are all 0 or are all 1, the value is invalid. if (masked == 0 || masked == RedundancyMask) { throw new CryptographicException(SR.Resource("Cryptography_Der_Invalid_Encoding")); } } Debug.Assert(!tag.IsConstructed); this.WriteTag(tag); this.WriteLength(value.Length); // WriteLength ensures the content-space value.CopyTo(this._buffer.AsSpan(this._offset)); this._offset += value.Length; } // T-REC-X.690-201508 sec 8.3 private void WriteIntegerCore(Asn1Tag tag, BigInteger value) { // TODO: Split this for netstandard vs netcoreapp for span-perf?. byte[] encoded = value.ToByteArray(); Array.Reverse(encoded); Debug.Assert(!tag.IsConstructed); this.WriteTag(tag); this.WriteLength(encoded.Length); Buffer.BlockCopy(encoded, 0, this._buffer, this._offset, encoded.Length); this._offset += encoded.Length; } } }