context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HSSF.Converter { using System; using System.Text; using System.IO; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.HSSF.Util; using NPOI.SS.Util; public class ExcelToHtmlUtils { private const short EXCEL_COLUMN_WIDTH_FACTOR = 256; private const int UNIT_OFFSET_LENGTH = 7; public static void AppendAlign(StringBuilder style, HorizontalAlignment alignment) { switch (alignment) { case HorizontalAlignment.Center: style.Append("text-align: center; "); break; case HorizontalAlignment.CenterSelection: style.Append("text-align: center; "); break; case HorizontalAlignment.Fill: // XXX: shall we support fill? break; case HorizontalAlignment.General: break; case HorizontalAlignment.Justify: style.Append("text-align: justify; "); break; case HorizontalAlignment.Left: style.Append("text-align: left; "); break; case HorizontalAlignment.Right: style.Append("text-align: right; "); break; } } /** * Creates a map (i.e. two-dimensional array) filled with ranges. Allow fast * retrieving {@link CellRangeAddress} of any cell, if cell is contained in * range. * * @see #getMergedRange(CellRangeAddress[][], int, int) */ public static CellRangeAddress[][] BuildMergedRangesMap(HSSFSheet sheet) { CellRangeAddress[][] mergedRanges = new CellRangeAddress[1][]; for ( int m = 0; m < sheet.NumMergedRegions; m++ ) { CellRangeAddress cellRangeAddress = sheet.GetMergedRegion( m ); int requiredHeight = cellRangeAddress.LastRow + 1; if ( mergedRanges.Length < requiredHeight ) { CellRangeAddress[][] newArray = new CellRangeAddress[requiredHeight][]; Array.Copy( mergedRanges, 0, newArray, 0, mergedRanges.Length ); mergedRanges = newArray; } for ( int r = cellRangeAddress.FirstRow; r <= cellRangeAddress.LastRow; r++ ) { int requiredWidth = cellRangeAddress.LastColumn + 1; CellRangeAddress[] rowMerged = mergedRanges[r]; if ( rowMerged == null ) { rowMerged = new CellRangeAddress[requiredWidth]; mergedRanges[r] = rowMerged; } else { int rowMergedLength = rowMerged.Length; if ( rowMergedLength < requiredWidth ) { CellRangeAddress[] newRow = new CellRangeAddress[requiredWidth]; Array.Copy(rowMerged, 0, newRow, 0,rowMergedLength ); mergedRanges[r] = newRow; rowMerged = newRow; } } //Arrays.Fill( rowMerged, cellRangeAddress.FirstColumn, cellRangeAddress.LastColumn + 1, cellRangeAddress ); for (int i = cellRangeAddress.FirstColumn; i < cellRangeAddress.LastColumn + 1; i++) { rowMerged[i] = cellRangeAddress; } } } return mergedRanges; } public static string GetBorderStyle(BorderStyle xlsBorder) { string borderStyle; switch (xlsBorder) { case BorderStyle.None: borderStyle = "none"; break; case BorderStyle.DashDot: case BorderStyle.DashDotDot: case BorderStyle.Dotted: case BorderStyle.Hair: case BorderStyle.MediumDashDot: case BorderStyle.MediumDashDotDot: case BorderStyle.SlantedDashDot: borderStyle = "dotted"; break; case BorderStyle.Dashed: case BorderStyle.MediumDashed: borderStyle = "dashed"; break; case BorderStyle.Double: borderStyle = "double"; break; default: borderStyle = "solid"; break; } return borderStyle; } public static string GetBorderWidth(BorderStyle xlsBorder) { string borderWidth; switch (xlsBorder) { case BorderStyle.MediumDashDot: case BorderStyle.MediumDashDotDot: case BorderStyle.MediumDashed: borderWidth = "2pt"; break; case BorderStyle.Thick: borderWidth = "thick"; break; default: borderWidth = "thin"; break; } return borderWidth; } public static string GetColor(HSSFColor color) { StringBuilder stringBuilder = new StringBuilder(7); stringBuilder.Append('#'); foreach (short s in color.GetTriplet()) { //if (s < 10) // stringBuilder.Append('0'); stringBuilder.Append(s.ToString("x2")); } string result = stringBuilder.ToString(); if (result.Equals("#ffffff")) return "white"; if (result.Equals("#c0c0c0")) return "silver"; if (result.Equals("#808080")) return "gray"; if (result.Equals("#000000")) return "black"; return result; } /** * See <a href= * "http://apache-poi.1045710.n5.nabble.com/Excel-Column-Width-Unit-Converter-pixels-excel-column-width-units-td2301481.html" * >here</a> for Xio explanation and details */ public static int GetColumnWidthInPx(int widthUnits) { int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) * UNIT_OFFSET_LENGTH; int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR; pixels += (int)Math.Round(offsetWidthUnits / ((float)EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH)); return pixels; } /** * @param mergedRanges * map of sheet merged ranges built with * {@link #buildMergedRangesMap(HSSFSheet)} * @return {@link CellRangeAddress} from map if cell with specified row and * column numbers contained in found range, <tt>null</tt> otherwise */ public static CellRangeAddress GetMergedRange( CellRangeAddress[][] mergedRanges, int rowNumber, int columnNumber) { CellRangeAddress[] mergedRangeRowInfo = rowNumber < mergedRanges.Length ? mergedRanges[rowNumber] : null; CellRangeAddress cellRangeAddress = mergedRangeRowInfo != null && columnNumber < mergedRangeRowInfo.Length ? mergedRangeRowInfo[columnNumber] : null; return cellRangeAddress; } public static HSSFWorkbook LoadXls(string xlsFile) { FileStream inputStream = File.Open(xlsFile, FileMode.Open); //FileInputStream inputStream = new FileInputStream( xlsFile ); try { return new HSSFWorkbook(inputStream); } finally { if (inputStream != null) inputStream.Close(); inputStream = null; //IOUtils.closeQuietly( inputStream ); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Expressions; using Newtonsoft.Json.Linq; using Xunit; namespace Microsoft.VisualStudio.Services.Agent.Tests { public sealed class ExpressionsL0 { //////////////////////////////////////////////////////////////////////////////// // Type-cast rules //////////////////////////////////////////////////////////////////////////////// [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void CastsToBoolean() { using (var hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(nameof(CastsToBoolean)); // Boolean trace.Info($"****************************************"); trace.Info($"From Boolean"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "true")); Assert.Equal(true, EvaluateBoolean(hc, "TRUE")); Assert.Equal(false, EvaluateBoolean(hc, "false")); Assert.Equal(false, EvaluateBoolean(hc, "FALSE")); // Number trace.Info($"****************************************"); trace.Info($"From Number"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "1")); Assert.Equal(true, EvaluateBoolean(hc, ".5")); Assert.Equal(true, EvaluateBoolean(hc, "0.5")); Assert.Equal(true, EvaluateBoolean(hc, "2")); Assert.Equal(true, EvaluateBoolean(hc, "-1")); Assert.Equal(true, EvaluateBoolean(hc, "-.5")); Assert.Equal(true, EvaluateBoolean(hc, "-0.5")); Assert.Equal(true, EvaluateBoolean(hc, "-2")); Assert.Equal(false, EvaluateBoolean(hc, "0")); Assert.Equal(false, EvaluateBoolean(hc, "0.0")); Assert.Equal(false, EvaluateBoolean(hc, "-0")); Assert.Equal(false, EvaluateBoolean(hc, "-0.0")); // String trace.Info($"****************************************"); trace.Info($"From String"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "'a'")); Assert.Equal(true, EvaluateBoolean(hc, "'false'")); Assert.Equal(true, EvaluateBoolean(hc, "'0'")); Assert.Equal(true, EvaluateBoolean(hc, "' '")); Assert.Equal(false, EvaluateBoolean(hc, "''")); // Version trace.Info($"****************************************"); trace.Info($"From Version"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "1.2.3")); Assert.Equal(true, EvaluateBoolean(hc, "1.2.3.4")); Assert.Equal(true, EvaluateBoolean(hc, "0.0.0")); // Objects/Arrays trace.Info($"****************************************"); trace.Info($"From Objects/Arrays"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "testFunction()", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new object())); Assert.Equal(true, EvaluateBoolean(hc, "testFunction()", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new object[0])); Assert.Equal(true, EvaluateBoolean(hc, "testFunction()", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new int[0])); Assert.Equal(true, EvaluateBoolean(hc, "testFunction()", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new Dictionary<string, object>())); Assert.Equal(true, EvaluateBoolean(hc, "testFunction()", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new JArray())); Assert.Equal(true, EvaluateBoolean(hc, "testFunction()", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new JObject())); // Null trace.Info($"****************************************"); trace.Info($"From Null"); trace.Info($"****************************************"); Assert.Equal(false, EvaluateBoolean(hc, "testFunction()", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: null)); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void CastsToNumber() { using (var hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(nameof(CastsToBoolean)); // Boolean trace.Info($"****************************************"); trace.Info($"From Boolean"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "eq(1, true)")); Assert.Equal(true, EvaluateBoolean(hc, "eq(0, false)")); // Number trace.Info($"****************************************"); trace.Info($"From String"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "eq(0, '')")); Assert.Equal(true, EvaluateBoolean(hc, "eq(123456.789, ' 123,456.789 ')")); Assert.Equal(true, EvaluateBoolean(hc, "eq(123456.789, ' +123,456.789 ')")); Assert.Equal(true, EvaluateBoolean(hc, "eq(-123456.789, ' -123,456.789 ')")); // Version trace.Info($"****************************************"); trace.Info($"From Version"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2, 1.2.0)")); Assert.Equal(true, EvaluateBoolean(hc, "ne(0, 0.0.0)")); // Objects/Arrays trace.Info($"****************************************"); trace.Info($"From Objects/Arrays"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "ne(0, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new object())); Assert.Equal(true, EvaluateBoolean(hc, "ne(0, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new object[0])); Assert.Equal(true, EvaluateBoolean(hc, "ne(0, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new int[0])); Assert.Equal(true, EvaluateBoolean(hc, "ne(0, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new Dictionary<string, object>())); Assert.Equal(true, EvaluateBoolean(hc, "ne(0, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new JArray())); Assert.Equal(true, EvaluateBoolean(hc, "ne(0, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new JObject())); Assert.Equal(true, EvaluateBoolean(hc, "ne(-1, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new object())); Assert.Equal(true, EvaluateBoolean(hc, "ne(1, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new object())); // Null trace.Info($"****************************************"); trace.Info($"From Null"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "eq('', testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: null)); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void CastsToString() { using (var hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(nameof(CastsToBoolean)); // Boolean trace.Info($"****************************************"); trace.Info($"From Boolean"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "eq('true', true)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('false', false)")); // Number trace.Info($"****************************************"); trace.Info($"From Number"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "eq('1', 1)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('0.5', .5)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('0.5', 0.5)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('2', 2)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('-1', -1)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('-0.5', -.5)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('-0.5', -0.5)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('-2', -2.0)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('0', 0)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('0', 0.0)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('0', -0)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('0', -0.0)")); // Version trace.Info($"****************************************"); trace.Info($"From Version"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "eq('1.2.3', 1.2.3)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('1.2.3.4', 1.2.3.4)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('0.0.0', 0.0.0)")); // Objects/Arrays trace.Info($"****************************************"); trace.Info($"From Objects/Arrays"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "ne('', testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new object())); Assert.Equal(true, EvaluateBoolean(hc, "ne('', testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new object[0])); Assert.Equal(true, EvaluateBoolean(hc, "ne('', testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new int[0])); Assert.Equal(true, EvaluateBoolean(hc, "ne('', testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new Dictionary<string, object>())); Assert.Equal(true, EvaluateBoolean(hc, "ne('', testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new JArray())); Assert.Equal(true, EvaluateBoolean(hc, "ne('', testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new JObject())); // Null trace.Info($"****************************************"); trace.Info($"From Null"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "eq('', testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: null)); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void CastsToVersion() { using (var hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(nameof(CastsToBoolean)); trace.Info($"****************************************"); trace.Info($"From Boolean"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "ne(0.0.0.0, false)")); trace.Info($"****************************************"); trace.Info($"From Number"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "eq(testFunction(), 1.2)", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new Version(1, 2))); Assert.Equal(false, EvaluateBoolean(hc, "eq(testFunction(), 1.0)", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new Version(1, 0))); trace.Info($"****************************************"); trace.Info($"From String"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "eq(1.2.3.4, '1.2.3.4')")); Assert.Equal(true, EvaluateBoolean(hc, "eq(1.2.3, '1.2.3')")); Assert.Equal(true, EvaluateBoolean(hc, "eq(testFunction(), '1.2')", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new Version(1, 2))); trace.Info($"****************************************"); trace.Info($"From Objects/Arrays"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2.3, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new object())); Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2.3, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new object[0])); Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2.3, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new int[0])); Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2.3, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new Dictionary<string, object>())); Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2.3, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new JArray())); Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2.3, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: new JObject())); // Null trace.Info($"****************************************"); trace.Info($"From Null"); trace.Info($"****************************************"); Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2.3, testFunction())", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: null)); } } //////////////////////////////////////////////////////////////////////////////// // JObject/JArray //////////////////////////////////////////////////////////////////////////////// [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void IndexesIntoComplex() { using (var hc = new TestHostContext(this)) { var obj = new JObject { { "subObj", new JObject { { "nestedProp1", "nested sub object property value 1" }, { "nestedProp2", "nested sub object property value 2" } } }, { "prop1", "property value 1" }, { "prop2", "property value 2" }, { "array", new JArray { "array element at index 0", "array element at index 1", } } }; Assert.Equal(true, EvaluateBoolean(hc, "eq('property value 1', testFunction()['prop1'])", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: obj)); Assert.Equal(true, EvaluateBoolean(hc, "eq('property value 2', testFunction().prop2)", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: obj)); Assert.Equal(true, EvaluateBoolean(hc, "eq('nested sub object property value 1', testFunction()['subObj']['nestedProp1'])", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: obj)); Assert.Equal(true, EvaluateBoolean(hc, "eq('nested sub object property value 2', testFunction()['subObj'].nestedProp2)", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: obj)); Assert.Equal(true, EvaluateBoolean(hc, "eq('nested sub object property value 1', testFunction().subObj['nestedProp1'])", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: obj)); Assert.Equal(true, EvaluateBoolean(hc, "eq('nested sub object property value 2', testFunction().subObj.nestedProp2)", functions: new IFunctionInfo[] { new FunctionInfo<TestFunctionNode>("testFunction", 0, 0) }, state: obj)); } } //////////////////////////////////////////////////////////////////////////////// // Built-in functions //////////////////////////////////////////////////////////////////////////////// [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesAnd() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "and(true, true, true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "and(true, true)")); Assert.Equal(false, EvaluateBoolean(hc, "and(true, true, false)")); Assert.Equal(false, EvaluateBoolean(hc, "and(true, false)")); Assert.Equal(false, EvaluateBoolean(hc, "and(false, true)")); Assert.Equal(false, EvaluateBoolean(hc, "and(false, false)")); Assert.Equal(true, EvaluateBoolean(hc, "and(true, 1)")); // number Assert.Equal(false, EvaluateBoolean(hc, "and(true, 0)")); Assert.Equal(true, EvaluateBoolean(hc, "and(true, 'a')")); // string Assert.Equal(false, EvaluateBoolean(hc, "and(true, '')")); Assert.Equal(true, EvaluateBoolean(hc, "and(true, 0.0.0.0)")); // version Assert.Equal(true, EvaluateBoolean(hc, "and(true, 1.2.3.4)")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void AndShortCircuitsAndAfterFirstFalse() { using (var hc = new TestHostContext(this)) { // The gt function should never evaluate. It would would throw since 'not a number' // cannot be converted to a number. Assert.Equal(false, EvaluateBoolean(hc, "and(false, gt(1, 'not a number'))")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesContains() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "contains('leading match', 'leading')")); Assert.Equal(true, EvaluateBoolean(hc, "contains('trailing match', 'match')")); Assert.Equal(true, EvaluateBoolean(hc, "contains('middle match', 'ddle mat')")); Assert.Equal(true, EvaluateBoolean(hc, "contains('case insensITIVE match', 'INSENSitive')")); Assert.Equal(false, EvaluateBoolean(hc, "contains('does not match', 'zzz')")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ContainsCastsToString() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "contains(true, true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "contains(true, 'ru')")); Assert.Equal(false, EvaluateBoolean(hc, "contains(true, 'zzz')")); Assert.Equal(false, EvaluateBoolean(hc, "contains(true, false)")); Assert.Equal(true, EvaluateBoolean(hc, "contains(123456789, 456)")); // number Assert.Equal(false, EvaluateBoolean(hc, "contains(123456789, 321)")); Assert.Equal(true, EvaluateBoolean(hc, "contains(1.2.3.4, 1.2.3)")); // version Assert.Equal(true, EvaluateBoolean(hc, "contains(1.2.3.4, 2.3)")); Assert.Equal(false, EvaluateBoolean(hc, "contains(1.2.3.4, 3.2)")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesEndsWith() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "endsWith('trailing match', 'match')")); Assert.Equal(true, EvaluateBoolean(hc, "endsWith('case insensITIVE', 'INSENSitive')")); Assert.Equal(false, EvaluateBoolean(hc, "endswith('leading does not match', 'leading')")); Assert.Equal(false, EvaluateBoolean(hc, "endswith('middle does not match', 'does not')")); Assert.Equal(false, EvaluateBoolean(hc, "endsWith('does not match', 'zzz')")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EndsWithCastsToString() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "endsWith(true, true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "endsWith(true, 'ue')")); Assert.Equal(false, EvaluateBoolean(hc, "endsWith(true, 'u')")); Assert.Equal(false, EvaluateBoolean(hc, "endsWith(true, false)")); Assert.Equal(true, EvaluateBoolean(hc, "endsWith(123456789, 789)")); // number Assert.Equal(false, EvaluateBoolean(hc, "endsWith(123456789, 8)")); Assert.Equal(true, EvaluateBoolean(hc, "endsWith(1.2.3.4, 3.4)")); // version Assert.Equal(false, EvaluateBoolean(hc, "endsWith(1.2.3.4, 3)")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesEqual() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "eq(true, true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "eq(false, false)")); Assert.Equal(false, EvaluateBoolean(hc, "eq(false, true)")); Assert.Equal(true, EvaluateBoolean(hc, "eq(2, 2)")); // number Assert.Equal(false, EvaluateBoolean(hc, "eq(1, 2)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('insensITIVE', 'INSENSitive')")); // string Assert.Equal(false, EvaluateBoolean(hc, "eq('a', 'b')")); Assert.Equal(true, EvaluateBoolean(hc, "eq(1.2.3, 1.2.3)")); // version Assert.Equal(false, EvaluateBoolean(hc, "eq(1.2.3, 1.2.3.0)")); Assert.Equal(false, EvaluateBoolean(hc, "eq(1.2.3, 4.5.6)")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EqualCastsToMatchLeftSide() { using (var hc = new TestHostContext(this)) { // Cast to bool. Assert.Equal(true, EvaluateBoolean(hc, "eq(true, 2)")); // number Assert.Equal(true, EvaluateBoolean(hc, "eq(false, 0)")); Assert.Equal(true, EvaluateBoolean(hc, "eq(true, 'a')")); // string Assert.Equal(true, EvaluateBoolean(hc, "eq(true, ' ')")); Assert.Equal(true, EvaluateBoolean(hc, "eq(false, '')")); Assert.Equal(true, EvaluateBoolean(hc, "eq(true, 1.2.3)")); // version Assert.Equal(true, EvaluateBoolean(hc, "eq(true, 0.0.0)")); // Cast to string. Assert.Equal(true, EvaluateBoolean(hc, "eq('TRue', true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "eq('FALse', false)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('123456.789', 123456.789)")); // number Assert.Equal(false, EvaluateBoolean(hc, "eq('123456.000', 123456.000)")); Assert.Equal(true, EvaluateBoolean(hc, "eq('1.2.3', 1.2.3)")); // version // Cast to number (best effort). Assert.Equal(true, EvaluateBoolean(hc, "eq(1, true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "eq(0, false)")); Assert.Equal(false, EvaluateBoolean(hc, "eq(2, true)")); Assert.Equal(true, EvaluateBoolean(hc, "eq(123456.789, ' +123,456.7890 ')")); // string Assert.Equal(true, EvaluateBoolean(hc, "eq(-123456.789, ' -123,456.7890 ')")); Assert.Equal(true, EvaluateBoolean(hc, "eq(123000, ' 123,000.000 ')")); Assert.Equal(true, EvaluateBoolean(hc, "eq(0, '')")); Assert.Equal(false, EvaluateBoolean(hc, "eq(1, 'not a number')")); Assert.Equal(false, EvaluateBoolean(hc, "eq(0, 'not a number')")); Assert.Equal(false, EvaluateBoolean(hc, "eq(1.2, 1.2.0.0)")); // version // Cast to version (best effort). Assert.Equal(false, EvaluateBoolean(hc, "eq(1.2.3, false)")); // bool Assert.Equal(false, EvaluateBoolean(hc, "eq(1.2.3, true)")); Assert.Equal(false, EvaluateBoolean(hc, "eq(1.2.0, 1.2)")); // number Assert.Equal(true, EvaluateBoolean(hc, "eq(1.2.0, ' 1.2.0 ')")); // string Assert.Equal(false, EvaluateBoolean(hc, "eq(1.2.0, '1.2')")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesGreaterThan() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "gt(true, false)")); // bool Assert.Equal(false, EvaluateBoolean(hc, "gt(true, true)")); Assert.Equal(false, EvaluateBoolean(hc, "gt(false, true)")); Assert.Equal(false, EvaluateBoolean(hc, "gt(false, false)")); Assert.Equal(true, EvaluateBoolean(hc, "gt(2, 1)")); // number Assert.Equal(false, EvaluateBoolean(hc, "gt(2, 2)")); Assert.Equal(false, EvaluateBoolean(hc, "gt(1, 2)")); Assert.Equal(true, EvaluateBoolean(hc, "gt('DEF', 'abc')")); // string Assert.Equal(true, EvaluateBoolean(hc, "gt('def', 'ABC')")); Assert.Equal(false, EvaluateBoolean(hc, "gt('a', 'a')")); Assert.Equal(false, EvaluateBoolean(hc, "gt('a', 'b')")); Assert.Equal(true, EvaluateBoolean(hc, "gt(4.5.6, 1.2.3)")); // version Assert.Equal(false, EvaluateBoolean(hc, "gt(1.2.3, 4.5.6)")); Assert.Equal(false, EvaluateBoolean(hc, "gt(1.2.3, 1.2.3)")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void GreaterThanCastsToMatchLeftSide() { using (var hc = new TestHostContext(this)) { // Cast to bool. Assert.Equal(true, EvaluateBoolean(hc, "gt(true, 0)")); // number Assert.Equal(false, EvaluateBoolean(hc, "gt(true, 1)")); Assert.Equal(true, EvaluateBoolean(hc, "gt(true, '')")); // string Assert.Equal(false, EvaluateBoolean(hc, "gt(true, ' ')")); Assert.Equal(false, EvaluateBoolean(hc, "gt(true, 'a')")); Assert.Equal(false, EvaluateBoolean(hc, "gt(true, 1.2.3)")); // version Assert.Equal(false, EvaluateBoolean(hc, "gt(true, 0.0.0)")); // Cast to string. Assert.Equal(true, EvaluateBoolean(hc, "gt('UUU', true)")); // bool Assert.Equal(false, EvaluateBoolean(hc, "gt('SSS', true)")); Assert.Equal(true, EvaluateBoolean(hc, "gt('123456.789', 123456.78)")); // number Assert.Equal(false, EvaluateBoolean(hc, "gt('123456.789', 123456.7899)")); Assert.Equal(true, EvaluateBoolean(hc, "gt('1.2.3', 1.2.2)")); // version Assert.Equal(false, EvaluateBoolean(hc, "gt('1.2.3', 1.2.4)")); // Cast to number (or fails). Assert.Equal(true, EvaluateBoolean(hc, "gt(1, false)")); // bool Assert.Equal(false, EvaluateBoolean(hc, "gt(1, true)")); Assert.Equal(true, EvaluateBoolean(hc, "gt(123456.789, ' +123,456.788 ')")); // string Assert.Equal(false, EvaluateBoolean(hc, "gt(123456.789, ' +123,456.7899 ')")); Assert.Equal(false, EvaluateBoolean(hc, "gt(123456.789, ' +123,456.789 ')")); Assert.Equal(true, EvaluateBoolean(hc, "gt(-123456.789, ' -123,456.7899 ')")); Assert.Equal(false, EvaluateBoolean(hc, "gt(-123456.789, ' -123,456.789 ')")); Assert.Equal(false, EvaluateBoolean(hc, "gt(-123456.789, ' -123,456.788 ')")); try { EvaluateBoolean(hc, "gt(1, 'not a number')"); throw new Exception("Should not reach here."); } catch (InvalidCastException ex) { Assert.Equal("String", GetFromKind(ex)); Assert.Equal("Number", GetToKind(ex)); Assert.Equal("not a number", GetValue(ex)); } try { EvaluateBoolean(hc, "gt(1.2, 1.2.0.0)"); // version throw new Exception("Should not reach here."); } catch (InvalidCastException ex) { Assert.Equal("Version", GetFromKind(ex)); Assert.Equal("Number", GetToKind(ex)); Assert.Equal(new Version("1.2.0.0"), GetValue(ex)); } // Cast to version (or fails). try { EvaluateBoolean(hc, "gt(1.2.3, false)"); // bool throw new Exception("Should not reach here."); } catch (InvalidCastException ex) { Assert.Equal("Boolean", GetFromKind(ex)); Assert.Equal("Version", GetToKind(ex)); Assert.Equal(false, GetValue(ex)); } Assert.Equal(true, EvaluateBoolean(hc, "gt(1.2.0, 1.1)")); // number Assert.Equal(false, EvaluateBoolean(hc, "gt(1.2.0, 1.3)")); try { EvaluateBoolean(hc, "gt(1.2.0, 2147483648.1)"); throw new Exception("Should not reach here."); } catch (InvalidCastException ex) { Assert.Equal("Number", GetFromKind(ex)); Assert.Equal("Version", GetToKind(ex)); Assert.Equal(2147483648.1m, GetValue(ex)); } Assert.Equal(true, EvaluateBoolean(hc, "gt(1.2.1, ' 1.2.0 ')")); // string Assert.Equal(false, EvaluateBoolean(hc, "gt(1.2.1, ' 1.2.1 ')")); Assert.Equal(false, EvaluateBoolean(hc, "gt(1.2.1, ' 1.2.2 ')")); try { EvaluateBoolean(hc, "gt(1.2.1, 'not a version')"); throw new Exception("Should not reach here."); } catch (InvalidCastException ex) { Assert.Equal("String", GetFromKind(ex)); Assert.Equal("Version", GetToKind(ex)); Assert.Equal("not a version", GetValue(ex)); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesGreaterThanOrEqual() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "ge(true, false)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "ge(true, true)")); Assert.Equal(false, EvaluateBoolean(hc, "ge(false, true)")); Assert.Equal(true, EvaluateBoolean(hc, "ge(2, 1)")); // number Assert.Equal(true, EvaluateBoolean(hc, "ge(2, 2)")); Assert.Equal(false, EvaluateBoolean(hc, "ge(1, 2)")); Assert.Equal(true, EvaluateBoolean(hc, "ge('DEF', 'abc')")); // string Assert.Equal(true, EvaluateBoolean(hc, "ge('def', 'ABC')")); Assert.Equal(true, EvaluateBoolean(hc, "ge('a', 'a')")); Assert.Equal(false, EvaluateBoolean(hc, "ge('a', 'b')")); Assert.Equal(true, EvaluateBoolean(hc, "ge(4.5.6, 1.2.3)")); // version Assert.Equal(true, EvaluateBoolean(hc, "ge(1.2.3, 1.2.3)")); Assert.Equal(false, EvaluateBoolean(hc, "ge(1.2.3, 4.5.6)")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesIn() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "in(true, false, false, true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "in(true, false, true, false)")); Assert.Equal(true, EvaluateBoolean(hc, "in(true, true, false, false)")); Assert.Equal(true, EvaluateBoolean(hc, "in(true, true)")); Assert.Equal(true, EvaluateBoolean(hc, "in(false, false)")); Assert.Equal(false, EvaluateBoolean(hc, "in(true, false, false, false)")); Assert.Equal(false, EvaluateBoolean(hc, "in(false, true)")); Assert.Equal(false, EvaluateBoolean(hc, "in(true, false)")); Assert.Equal(true, EvaluateBoolean(hc, "in(2, 1, 2, 3)")); // number Assert.Equal(false, EvaluateBoolean(hc, "in(2, 1, 3, 4)")); Assert.Equal(true, EvaluateBoolean(hc, "in('insensITIVE', 'other', 'INSENSitive')")); // string Assert.Equal(false, EvaluateBoolean(hc, "in('a', 'b', 'c')")); Assert.Equal(true, EvaluateBoolean(hc, "in(1.2.3, 1.1.1, 1.2.3)")); // version Assert.Equal(false, EvaluateBoolean(hc, "in(1.2.3, 4.5.6)")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void InCastsToMatchLeftSide() { using (var hc = new TestHostContext(this)) { // Cast to bool. Assert.Equal(true, EvaluateBoolean(hc, "in(true, 2)")); // number Assert.Equal(true, EvaluateBoolean(hc, "in(false, 0)")); Assert.Equal(true, EvaluateBoolean(hc, "in(true, 'a')")); // string Assert.Equal(true, EvaluateBoolean(hc, "in(true, ' ')")); Assert.Equal(true, EvaluateBoolean(hc, "in(false, '')")); Assert.Equal(true, EvaluateBoolean(hc, "in(true, 1.2.3)")); // version Assert.Equal(true, EvaluateBoolean(hc, "in(true, 0.0.0)")); // Cast to string. Assert.Equal(true, EvaluateBoolean(hc, "in('TRue', true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "in('FALse', false)")); Assert.Equal(true, EvaluateBoolean(hc, "in('123456.789', 123456.789)")); // number Assert.Equal(false, EvaluateBoolean(hc, "in('123456.000', 123456.000)")); Assert.Equal(true, EvaluateBoolean(hc, "in('1.2.3', 1.2.3)")); // version // Cast to number (best effort). Assert.Equal(true, EvaluateBoolean(hc, "in(1, true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "in(0, false)")); Assert.Equal(false, EvaluateBoolean(hc, "in(2, true)")); Assert.Equal(true, EvaluateBoolean(hc, "in(123456.789, ' +123,456.7890 ')")); // string Assert.Equal(true, EvaluateBoolean(hc, "in(-123456.789, ' -123,456.7890 ')")); Assert.Equal(true, EvaluateBoolean(hc, "in(123000, ' 123,000.000 ')")); Assert.Equal(true, EvaluateBoolean(hc, "in(0, '')")); Assert.Equal(false, EvaluateBoolean(hc, "in(1, 'not a number')")); Assert.Equal(false, EvaluateBoolean(hc, "in(0, 'not a number')")); Assert.Equal(false, EvaluateBoolean(hc, "in(1.2, 1.2.0.0)")); // version // Cast to version (best effort). Assert.Equal(false, EvaluateBoolean(hc, "in(1.2.3, false)")); // bool Assert.Equal(false, EvaluateBoolean(hc, "in(1.2.3, true)")); Assert.Equal(false, EvaluateBoolean(hc, "in(1.2.0, 1.2)")); // number Assert.Equal(true, EvaluateBoolean(hc, "in(1.2.0, ' 1.2.0 ')")); // string Assert.Equal(false, EvaluateBoolean(hc, "in(1.2.0, '1.2')")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void InShortCircuitsAfterFirstMatch() { using (var hc = new TestHostContext(this)) { // The gt function should never evaluate. It would would throw since 'not a number' // cannot be converted to a number. Assert.Equal(true, EvaluateBoolean(hc, "in(true, true, gt(1, 'not a number'))")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesLessThan() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "lt(false, true)")); // bool Assert.Equal(false, EvaluateBoolean(hc, "lt(false, false)")); Assert.Equal(false, EvaluateBoolean(hc, "lt(true, false)")); Assert.Equal(false, EvaluateBoolean(hc, "lt(true, true)")); Assert.Equal(true, EvaluateBoolean(hc, "lt(1, 2)")); // number Assert.Equal(false, EvaluateBoolean(hc, "lt(1, 1)")); Assert.Equal(false, EvaluateBoolean(hc, "lt(2, 1)")); Assert.Equal(true, EvaluateBoolean(hc, "lt('abc', 'DEF')")); // string Assert.Equal(true, EvaluateBoolean(hc, "lt('abc', 'DEF')")); Assert.Equal(false, EvaluateBoolean(hc, "lt('a', 'a')")); Assert.Equal(false, EvaluateBoolean(hc, "lt('b', 'a')")); Assert.Equal(true, EvaluateBoolean(hc, "lt(1.2.3, 4.5.6)")); // version Assert.Equal(false, EvaluateBoolean(hc, "lt(4.5.6, 1.2.3)")); Assert.Equal(false, EvaluateBoolean(hc, "lt(1.2.3, 1.2.3)")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void LessThanCastsToMatchLeftSide() { using (var hc = new TestHostContext(this)) { // Cast to bool. Assert.Equal(true, EvaluateBoolean(hc, "lt(false, 1)")); // number Assert.Equal(false, EvaluateBoolean(hc, "lt(false, 0)")); Assert.Equal(true, EvaluateBoolean(hc, "lt(false, 'a')")); // string Assert.Equal(true, EvaluateBoolean(hc, "lt(false, ' ')")); Assert.Equal(false, EvaluateBoolean(hc, "lt(false, '')")); Assert.Equal(true, EvaluateBoolean(hc, "lt(false, 1.2.3)")); // version Assert.Equal(true, EvaluateBoolean(hc, "lt(false, 0.0.0)")); Assert.Equal(false, EvaluateBoolean(hc, "lt(true, 1.2.3)")); // Cast to string. Assert.Equal(true, EvaluateBoolean(hc, "lt('SSS', true)")); // bool Assert.Equal(false, EvaluateBoolean(hc, "lt('UUU', true)")); Assert.Equal(true, EvaluateBoolean(hc, "lt('123456.78', 123456.789)")); // number Assert.Equal(false, EvaluateBoolean(hc, "lt('123456.7899', 123456.789)")); Assert.Equal(true, EvaluateBoolean(hc, "lt('1.2.2', 1.2.3)")); // version Assert.Equal(false, EvaluateBoolean(hc, "lt('1.2.4', 1.2.3)")); // Cast to number (or fails). Assert.Equal(true, EvaluateBoolean(hc, "lt(0, true)")); // bool Assert.Equal(false, EvaluateBoolean(hc, "lt(0, false)")); Assert.Equal(true, EvaluateBoolean(hc, "lt(123456.788, ' +123,456.789 ')")); // string Assert.Equal(false, EvaluateBoolean(hc, "lt(123456.7899, ' +123,456.789 ')")); Assert.Equal(false, EvaluateBoolean(hc, "lt(123456.789, ' +123,456.789 ')")); Assert.Equal(true, EvaluateBoolean(hc, "lt(-123456.7899, ' -123,456.789 ')")); Assert.Equal(false, EvaluateBoolean(hc, "lt(-123456.789, ' -123,456.789 ')")); Assert.Equal(false, EvaluateBoolean(hc, "lt(-123456.788, ' -123,456.789 ')")); try { EvaluateBoolean(hc, "lt(1, 'not a number')"); throw new Exception("Should not reach here."); } catch (InvalidCastException ex) { Assert.Equal("String", GetFromKind(ex)); Assert.Equal("Number", GetToKind(ex)); Assert.Equal("not a number", GetValue(ex)); } try { EvaluateBoolean(hc, "lt(1.2, 1.2.0.0)"); // version throw new Exception("Should not reach here."); } catch (InvalidCastException ex) { Assert.Equal("Version", GetFromKind(ex)); Assert.Equal("Number", GetToKind(ex)); Assert.Equal(new Version("1.2.0.0"), GetValue(ex)); } // Cast to version (or fails). try { EvaluateBoolean(hc, "lt(1.2.3, false)"); // bool throw new Exception("Should not reach here."); } catch (InvalidCastException ex) { Assert.Equal("Boolean", GetFromKind(ex)); Assert.Equal("Version", GetToKind(ex)); Assert.Equal(false, GetValue(ex)); } Assert.Equal(true, EvaluateBoolean(hc, "lt(1.1.0, 1.2)")); // number Assert.Equal(false, EvaluateBoolean(hc, "lt(1.3.0, 1.2)")); try { EvaluateBoolean(hc, "lt(1.2.0, 2147483648.1)"); throw new Exception("Should not reach here."); } catch (InvalidCastException ex) { Assert.Equal("Number", GetFromKind(ex)); Assert.Equal("Version", GetToKind(ex)); Assert.Equal(2147483648.1m, GetValue(ex)); } Assert.Equal(true, EvaluateBoolean(hc, "lt(1.2.0, ' 1.2.1 ')")); // string Assert.Equal(false, EvaluateBoolean(hc, "lt(1.2.1, ' 1.2.1 ')")); Assert.Equal(false, EvaluateBoolean(hc, "lt(1.2.2, ' 1.2.1 ')")); try { EvaluateBoolean(hc, "lt(1.2.1, 'not a version')"); throw new Exception("Should not reach here."); } catch (InvalidCastException ex) { Assert.Equal("String", GetFromKind(ex)); Assert.Equal("Version", GetToKind(ex)); Assert.Equal("not a version", GetValue(ex)); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesLessThanOrEqual() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "le(false, true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "le(false, false)")); Assert.Equal(false, EvaluateBoolean(hc, "le(true, false)")); Assert.Equal(true, EvaluateBoolean(hc, "le(1, 2)")); // number Assert.Equal(true, EvaluateBoolean(hc, "le(2, 2)")); Assert.Equal(false, EvaluateBoolean(hc, "le(2, 1)")); Assert.Equal(true, EvaluateBoolean(hc, "le('abc', 'DEF')")); // string Assert.Equal(true, EvaluateBoolean(hc, "le('ABC', 'def')")); Assert.Equal(true, EvaluateBoolean(hc, "le('a', 'a')")); Assert.Equal(false, EvaluateBoolean(hc, "le('b', 'a')")); Assert.Equal(true, EvaluateBoolean(hc, "le(1.2.3, 4.5.6)")); // version Assert.Equal(true, EvaluateBoolean(hc, "le(1.2.3, 1.2.3)")); Assert.Equal(false, EvaluateBoolean(hc, "le(4.5.6, 1.2.3)")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesNot() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "not(false)")); // bool Assert.Equal(false, EvaluateBoolean(hc, "not(true)")); Assert.Equal(true, EvaluateBoolean(hc, "not(0)")); // number Assert.Equal(false, EvaluateBoolean(hc, "not(1)")); Assert.Equal(true, EvaluateBoolean(hc, "not('')")); // string Assert.Equal(false, EvaluateBoolean(hc, "not('a')")); Assert.Equal(false, EvaluateBoolean(hc, "not(' ')")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesNotEqual() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "ne(false, true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "ne(true, false)")); Assert.Equal(false, EvaluateBoolean(hc, "ne(false, false)")); Assert.Equal(false, EvaluateBoolean(hc, "ne(true, true)")); Assert.Equal(true, EvaluateBoolean(hc, "ne(1, 2)")); // number Assert.Equal(false, EvaluateBoolean(hc, "ne(2, 2)")); Assert.Equal(true, EvaluateBoolean(hc, "ne('abc', 'def')")); // string Assert.Equal(false, EvaluateBoolean(hc, "ne('abcDEF', 'ABCdef')")); Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2.3, 1.2.3.0)")); // version Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2.3, 4.5.6)")); Assert.Equal(false, EvaluateBoolean(hc, "ne(1.2.3, 1.2.3)")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void NotEqualCastsToMatchLeftSide() { using (var hc = new TestHostContext(this)) { // Cast to bool. Assert.Equal(true, EvaluateBoolean(hc, "ne(false, 2)")); // number Assert.Equal(true, EvaluateBoolean(hc, "ne(true, 0)")); Assert.Equal(true, EvaluateBoolean(hc, "ne(false, 'a')")); // string Assert.Equal(true, EvaluateBoolean(hc, "ne(false, ' ')")); Assert.Equal(true, EvaluateBoolean(hc, "ne(true, '')")); Assert.Equal(true, EvaluateBoolean(hc, "ne(false, 1.2.3)")); // version Assert.Equal(true, EvaluateBoolean(hc, "ne(false, 0.0.0)")); // Cast to string. Assert.Equal(false, EvaluateBoolean(hc, "ne('TRue', true)")); // bool Assert.Equal(false, EvaluateBoolean(hc, "ne('FALse', false)")); Assert.Equal(true, EvaluateBoolean(hc, "ne('123456.000', 123456.000)")); // number Assert.Equal(false, EvaluateBoolean(hc, "ne('123456.789', 123456.789)")); Assert.Equal(true, EvaluateBoolean(hc, "ne('1.2.3.0', 1.2.3)")); // version Assert.Equal(false, EvaluateBoolean(hc, "ne('1.2.3', 1.2.3)")); // Cast to number (best effort). Assert.Equal(true, EvaluateBoolean(hc, "ne(2, true)")); // bool Assert.Equal(false, EvaluateBoolean(hc, "ne(1, true)")); Assert.Equal(false, EvaluateBoolean(hc, "ne(0, false)")); Assert.Equal(false, EvaluateBoolean(hc, "ne(123456.789, ' +123,456.7890 ')")); // string Assert.Equal(false, EvaluateBoolean(hc, "ne(-123456.789, ' -123,456.7890 ')")); Assert.Equal(false, EvaluateBoolean(hc, "ne(123000, ' 123,000.000 ')")); Assert.Equal(false, EvaluateBoolean(hc, "ne(0, '')")); Assert.Equal(true, EvaluateBoolean(hc, "ne(1, 'not a number')")); Assert.Equal(true, EvaluateBoolean(hc, "ne(0, 'not a number')")); Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2, 1.2.0.0)")); // version // Cast to version (best effort). Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2.3, false)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2.3, true)")); Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2.0, 1.2)")); // number Assert.Equal(false, EvaluateBoolean(hc, "ne(1.2.0, ' 1.2.0 ')")); // string Assert.Equal(true, EvaluateBoolean(hc, "ne(1.2.0, '1.2')")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesNotIn() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "notIn(true, false, false, false)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "notIn(true, false)")); Assert.Equal(true, EvaluateBoolean(hc, "notIn(false, true)")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(true, false, true, true)")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(true, false, true, false)")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(true, true, false, false)")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(true, true)")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(false, false)")); Assert.Equal(true, EvaluateBoolean(hc, "notIn(2, 1, 3, 4)")); // number Assert.Equal(false, EvaluateBoolean(hc, "notIn(2, 1, 2, 3)")); Assert.Equal(true, EvaluateBoolean(hc, "notIn('a', 'b', 'c')")); // string Assert.Equal(false, EvaluateBoolean(hc, "notIn('insensITIVE', 'INSENSitive')")); Assert.Equal(true, EvaluateBoolean(hc, "notIn(1.2.2, 1.1.1, 1.3.3)")); // version Assert.Equal(false, EvaluateBoolean(hc, "notIn(1.2.2, 1.1.1, 1.2.2)")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void NotInCastsToMatchLeftSide() { using (var hc = new TestHostContext(this)) { // Cast to bool. Assert.Equal(true, EvaluateBoolean(hc, "notIn(true, 0)")); // number Assert.Equal(true, EvaluateBoolean(hc, "notIn(false, 1)")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(true, 1)")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(false, 0)")); Assert.Equal(true, EvaluateBoolean(hc, "notIn(false, 'a')")); // string Assert.Equal(true, EvaluateBoolean(hc, "notIn(false, ' ')")); Assert.Equal(true, EvaluateBoolean(hc, "notIn(true, '')")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(true, 'a')")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(true, ' ')")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(false, '')")); Assert.Equal(true, EvaluateBoolean(hc, "notIn(false, 1.2.3)")); // version Assert.Equal(false, EvaluateBoolean(hc, "notIn(true, 0.0.0)")); // Cast to string. Assert.Equal(true, EvaluateBoolean(hc, "notIn('TRue', false)")); // bool Assert.Equal(false, EvaluateBoolean(hc, "notIn('TRue', true)")); Assert.Equal(false, EvaluateBoolean(hc, "notIn('FALse', false)")); Assert.Equal(true, EvaluateBoolean(hc, "notIn('123456.000', 123456.000)")); // number Assert.Equal(false, EvaluateBoolean(hc, "notIn('123456.789', 123456.789)")); Assert.Equal(true, EvaluateBoolean(hc, "notIn('1.2.3', 1.2.4)")); // version Assert.Equal(false, EvaluateBoolean(hc, "notIn('1.2.3', 1.2.3)")); // Cast to number (best effort). Assert.Equal(true, EvaluateBoolean(hc, "notIn(2, true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "notIn(1, false)")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(1, true)")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(0, false)")); Assert.Equal(true, EvaluateBoolean(hc, "notIn(1, 'not a number')")); // string Assert.Equal(true, EvaluateBoolean(hc, "notIn(0, 'not a number')")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(123456.789, ' +123,456.7890 ')")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(-123456.789, ' -123,456.7890 ')")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(123000, ' 123,000.000 ')")); Assert.Equal(false, EvaluateBoolean(hc, "notIn(0, '')")); Assert.Equal(true, EvaluateBoolean(hc, "notIn(1.2, 1.2.0.0)")); // version // Cast to version (best effort). Assert.Equal(true, EvaluateBoolean(hc, "notIn(1.2.3, false)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "notIn(1.2.0, 1.2)")); // number Assert.Equal(false, EvaluateBoolean(hc, "notIn(1.2.0, ' 1.2.0 ')")); // string Assert.Equal(true, EvaluateBoolean(hc, "notIn(1.2.0, '1.2')")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void NotInShortCircuitsAfterFirstMatch() { using (var hc = new TestHostContext(this)) { // The gt function should never evaluate. It would would throw since 'not a number' // cannot be converted to a number. Assert.Equal(false, EvaluateBoolean(hc, "notIn(true, true, gt(1, 'not a number'))")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesOr() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "or(false, false, true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "or(false, true, false)")); Assert.Equal(true, EvaluateBoolean(hc, "or(true, false, false)")); Assert.Equal(false, EvaluateBoolean(hc, "or(false, false, false)")); Assert.Equal(true, EvaluateBoolean(hc, "or(false, 1)")); // number Assert.Equal(false, EvaluateBoolean(hc, "or(false, 0)")); Assert.Equal(true, EvaluateBoolean(hc, "or(false, 'a')")); // string Assert.Equal(false, EvaluateBoolean(hc, "or(false, '')")); Assert.Equal(true, EvaluateBoolean(hc, "or(false, 1.2.3)")); // version Assert.Equal(true, EvaluateBoolean(hc, "or(false, 0.0.0)")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void OrShortCircuitsAfterFirstTrue() { using (var hc = new TestHostContext(this)) { // The gt function should never evaluate. It would would throw since 'not a number' // cannot be converted to a number. Assert.Equal(true, EvaluateBoolean(hc, "or(true, gt(1, 'not a number'))")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesStartsWith() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "startsWith('leading match', 'leading')")); Assert.Equal(true, EvaluateBoolean(hc, "startsWith('insensITIVE case', 'INSENSitive')")); Assert.Equal(false, EvaluateBoolean(hc, "startsWith('does not match trailing', 'trailing')")); Assert.Equal(false, EvaluateBoolean(hc, "startsWith('middle does not match', 'does not')")); Assert.Equal(false, EvaluateBoolean(hc, "startsWith('does not match', 'zzz')")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void StartsWithCastsToString() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "startsWith(true, true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "startsWith(true, 'tr')")); Assert.Equal(false, EvaluateBoolean(hc, "startsWith(true, 'u')")); Assert.Equal(false, EvaluateBoolean(hc, "startsWith(true, false)")); Assert.Equal(true, EvaluateBoolean(hc, "startsWith(123456789, 123)")); // number Assert.Equal(false, EvaluateBoolean(hc, "startsWith(123456789, 8)")); Assert.Equal(true, EvaluateBoolean(hc, "startsWith(1.2.3.4, 1.2)")); // version Assert.Equal(false, EvaluateBoolean(hc, "startsWith(1.2.3.4, 3)")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void EvaluatesXor() { using (var hc = new TestHostContext(this)) { Assert.Equal(true, EvaluateBoolean(hc, "xor(false, true)")); // bool Assert.Equal(true, EvaluateBoolean(hc, "xor(true, false)")); Assert.Equal(false, EvaluateBoolean(hc, "xor(false, false)")); Assert.Equal(false, EvaluateBoolean(hc, "xor(true, true)")); Assert.Equal(true, EvaluateBoolean(hc, "xor(false, 1)")); // number Assert.Equal(false, EvaluateBoolean(hc, "xor(false, 0)")); Assert.Equal(true, EvaluateBoolean(hc, "xor(false, 'a')")); // string Assert.Equal(false, EvaluateBoolean(hc, "xor(false, '')")); Assert.Equal(true, EvaluateBoolean(hc, "xor(false, 1.2.3)")); // version Assert.Equal(true, EvaluateBoolean(hc, "xor(false, 0.0.0)")); } } //////////////////////////////////////////////////////////////////////////////// // Extension functions/values //////////////////////////////////////////////////////////////////////////////// [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ExtensionNamedValueReceivesState() { using (var hc = new TestHostContext(this)) { // Property syntax. bool actual = EvaluateBoolean( hc, "eq('lookup-value', testNamedValue.lookupKey)", namedValues: new[] { new NamedValueInfo<TestNamedValueNode>("testNamedValue") }, state: new Dictionary<string, object>() { { "lookupKey", "lookup-value" } }); Assert.True(actual); // Indexer syntax. actual = EvaluateBoolean( hc, "eq('lookup-value', testNamedValue['lookupKey'])", namedValues: new[] { new NamedValueInfo<TestNamedValueNode>("testNamedValue") }, state: new Dictionary<string, object>() { { "lookupKey", "lookup-value" } }); Assert.True(actual); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ExtensionFunctionReceivesState() { using (var hc = new TestHostContext(this)) { bool actual = EvaluateBoolean( hc, "eq('lookup-value', testFunction('lookup-key'))", functions: new[] { new FunctionInfo<TestFunctionNode>("testFunction", 1, 1) }, state: new Dictionary<string, object>() { { "lookup-key", "lookup-value" } }); Assert.True(actual); } } //////////////////////////////////////////////////////////////////////////////// // Unknown keywords //////////////////////////////////////////////////////////////////////////////// [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ValidateSyntax_AllowsUnknownFunction() { using (var hc = new TestHostContext(this)) { var parser = new Parser(); parser.ValidateSyntax( "or(eq(1, noSuchFunctionWithZeroParameters()), eq(2, noSuchFunctionWithManyParameters(1,2,3,4,5,6,7,8,9,10)))", new TraceWriter(hc)); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ValidateSyntax_AllowsUnknownNamedValues() { using (var hc = new TestHostContext(this)) { // Property dereference syntax. var parser = new Parser(); parser.ValidateSyntax( "eq(1, noSuchNamedValue.foo)", new TraceWriter(hc)); // Index syntax. parser.ValidateSyntax( "eq(1, noSuchNamedValue['foo'])", new TraceWriter(hc)); } } //////////////////////////////////////////////////////////////////////////////// // Parse exceptions //////////////////////////////////////////////////////////////////////////////// [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ThrowsWhenInvalidNumber() { using (var hc = new TestHostContext(this)) { try { EvaluateBoolean(hc, "eq(1.2, 3.4a)"); throw new Exception("Should not reach here."); } catch (ParseException ex) { Assert.Equal("UnrecognizedValue", GetKind(ex)); Assert.Equal("3.4a", GetRawToken(ex)); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ThrowsWhenInvalidString() { using (var hc = new TestHostContext(this)) { try { EvaluateBoolean(hc, "eq('hello', 'unterminated-string)"); throw new Exception("Should not reach here."); } catch (ParseException ex) { Assert.Equal("UnrecognizedValue", GetKind(ex)); Assert.Equal("'unterminated-string)", GetRawToken(ex)); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ThrowsWhenInvalidVersion() { using (var hc = new TestHostContext(this)) { try { EvaluateBoolean(hc, "eq(1.2.3, 4.5.6.7a)"); throw new Exception("Should not reach here."); } catch (ParseException ex) { Assert.Equal("UnrecognizedValue", GetKind(ex)); Assert.Equal("4.5.6.7a", GetRawToken(ex)); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ThrowsWhenExceededMaxDepth() { using (var hc = new TestHostContext(this)) { // 50 levels should work. EvaluateBoolean(hc, "not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(true)))))))))))))))))))))))))))))))))))))))))))))))))"); // 51 levels should not work. try { EvaluateBoolean(hc, "not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(true))))))))))))))))))))))))))))))))))))))))))))))))))"); throw new Exception("Should not reach here."); } catch (ParseException ex) { Assert.Equal("ExceededMaxDepth", GetKind(ex)); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ThrowsWhenExceededMaxLength() { using (var hc = new TestHostContext(this)) { // 2000 length should work. const string Format = "or('{0}', true)"; EvaluateBoolean(hc, string.Format(CultureInfo.InvariantCulture, Format, string.Empty.PadRight(2000 - Format.Length + "{0}".Length, 'a'))); // 2001 length should not work. try { EvaluateBoolean(hc, string.Format(CultureInfo.InvariantCulture, Format, string.Empty.PadRight(2001 - Format.Length + "{0}".Length, 'a'))); throw new Exception("Should not reach here."); } catch (ParseException ex) { Assert.Equal("ExceededMaxLength", GetKind(ex)); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ThrowsWhenExpectedStartParameter() { using (var hc = new TestHostContext(this)) { try { EvaluateBoolean(hc, "not(eq 1,2)"); throw new Exception("Should not reach here."); } catch (ParseException ex) { Assert.Equal("ExpectedStartParameter", GetKind(ex)); Assert.Equal("eq", GetRawToken(ex)); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ThrowsWhenUnclosedFunction() { using (var hc = new TestHostContext(this)) { try { EvaluateBoolean(hc, "eq(1,2"); throw new Exception("Should not reach here."); } catch (ParseException ex) { Assert.Equal("UnclosedFunction", GetKind(ex)); Assert.Equal("eq", GetRawToken(ex)); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ThrowsWhenUnknownFunction() { using (var hc = new TestHostContext(this)) { try { EvaluateBoolean(hc, "eq(1, noSuchFunction())"); throw new Exception("Should not reach here."); } catch (ParseException ex) { Assert.Equal("UnrecognizedValue", GetKind(ex)); Assert.Equal("noSuchFunction", GetRawToken(ex)); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ThrowsWhenUnknownNamedValue() { using (var hc = new TestHostContext(this)) { try { EvaluateBoolean(hc, "eq(1, noSuchNamedValue.foo)"); throw new Exception("Should not reach here."); } catch (ParseException ex) { Assert.Equal("UnrecognizedValue", GetKind(ex)); Assert.Equal("noSuchNamedValue", GetRawToken(ex)); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ValidateSyntax_ThrowsWhenExceededMaxDepth() { using (var hc = new TestHostContext(this)) { // 50 levels should work. var parser = new Parser(); parser.ValidateSyntax( "not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(true)))))))))))))))))))))))))))))))))))))))))))))))))", new TraceWriter(hc)); // 51 levels should not work. try { parser.ValidateSyntax( "not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(not(true))))))))))))))))))))))))))))))))))))))))))))))))))", new TraceWriter(hc)); throw new Exception("Should not reach here."); } catch (ParseException ex) { Assert.Equal("ExceededMaxDepth", GetKind(ex)); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void ValidateSyntax_ThrowsWhenExceededMaxLength() { using (var hc = new TestHostContext(this)) { // 2000 length should work. const string Format = "or('{0}', true)"; var parser = new Parser(); parser.ValidateSyntax( string.Format(CultureInfo.InvariantCulture, Format, string.Empty.PadRight(2000 - Format.Length + "{0}".Length, 'a')), new TraceWriter(hc)); // 2001 length should not work. try { parser.ValidateSyntax( string.Format(CultureInfo.InvariantCulture, Format, string.Empty.PadRight(2001 - Format.Length + "{0}".Length, 'a')), new TraceWriter(hc)); throw new Exception("Should not reach here."); } catch (ParseException ex) { Assert.Equal("ExceededMaxLength", GetKind(ex)); } } } //////////////////////////////////////////////////////////////////////////////// // Private //////////////////////////////////////////////////////////////////////////////// private static bool EvaluateBoolean( IHostContext hostContext, string expression, IEnumerable<INamedValueInfo> namedValues = null, IEnumerable<IFunctionInfo> functions = null, object state = null) { var parser = new Parser(); INode node = parser.CreateTree(expression, new TraceWriter(hostContext), namedValues, functions); return node.EvaluateBoolean(new TraceWriter(hostContext), state); } private static string GetFromKind(InvalidCastException ex) { return (ex.GetType().GetTypeInfo().GetProperty("FromKind", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic).GetValue(ex) as object).ToString(); } private static string GetToKind(InvalidCastException ex) { return (ex.GetType().GetTypeInfo().GetProperty("ToKind", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic).GetValue(ex) as object).ToString(); } private static object GetValue(InvalidCastException ex) { return ex.GetType().GetTypeInfo().GetProperty("Value", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic).GetValue(ex) as object; } private static string GetKind(ParseException ex) { return (ex.GetType().GetTypeInfo().GetProperty("Kind", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic).GetValue(ex) as object).ToString(); } private static string GetRawToken(ParseException ex) { return ex.GetType().GetTypeInfo().GetProperty("RawToken", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic).GetValue(ex) as string; } private sealed class TraceWriter : ITraceWriter { private readonly IHostContext _context; private readonly Tracing _trace; public TraceWriter(IHostContext context) { _context = context; _trace = context.GetTrace("ExpressionManager"); } public void Info(string message) { _trace.Info(message); } public void Verbose(string message) { _trace.Verbose(message); } } private sealed class TestNamedValueNode : NamedValueNode { public override string Name => "testNamedValue"; protected override object EvaluateCore(EvaluationContext context) { return context.State; } } private sealed class TestFunctionNode : FunctionNode { public override string Name => "testFunction"; protected override object EvaluateCore(EvaluationContext context) { if (Parameters.Count == 0) { return context.State; } string key = string.Join(",", Parameters.Select(x => x.EvaluateString(context))); var dictionary = context.State as IDictionary<string, object>; return dictionary[key]; } } } }
// // 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 FearTheCowboy.Iso19770.Schema { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml.Linq; using System.Xml.XPath; using Common.Core; using Newtonsoft.Json.Linq; using XmlExtensions = Utility.XmlExtensions; public class IdentityIndex { public static readonly JObject Context; private static readonly Dictionary<string, Identity> _viaJsonName = new Dictionary<string, Identity>(); private static readonly Dictionary<XName, Identity> _viaXname = new Dictionary<XName, Identity>(); static IdentityIndex() { Context = new JObject(); foreach (var decl in Namespace.Declarations.Where(each => each.Value.IndexOf("xml") != 0)) { Context.Add(decl.Value, decl.Key.NamespaceName + "#"); } // swid elements AddIdentity(SoftwareIdentity.Elements.Link, SoftwareIdentity.Attributes.HRef); AddIdentity(SoftwareIdentity.Elements.Directory, SoftwareIdentity.Attributes.Name); AddIdentity(SoftwareIdentity.Elements.File, SoftwareIdentity.Attributes.Name); AddIdentity(SoftwareIdentity.Elements.Entity, SoftwareIdentity.Attributes.RegId); AddIdentity(SoftwareIdentity.Elements.Process, SoftwareIdentity.Attributes.Name); AddIdentity(SoftwareIdentity.Elements.Resource, SoftwareIdentity.Attributes.Type); AddIdentity(SoftwareIdentity.Elements.Meta, null); AddIdentity(Discovery.Elements.Parameter, Discovery.Attributes.Name); // attributes foreach(var field in new[] {typeof (SoftwareIdentity.Attributes), typeof (Installation.Attributes), typeof (Discovery.Attributes)}.SelectMany(type => type.GetFields(BindingFlags.Static | BindingFlags.Public).Where(each => each.FieldType == typeof (XName)))) { try { AddIdentity((XName)field.GetValue(null)); } catch (Exception e) { e.Dump(); } } Context = new JObject(new JProperty("@context", Context)); } internal Identity this[string name] { get { if (_viaJsonName.ContainsKey(name)) { return _viaJsonName[name]; } return null; } } internal Identity this[XName name] { get { if (_viaXname.ContainsKey(name)) { return _viaXname[name]; } return null; } } private static void AddIdentity(XName name, XName index) { var i = new Identity { XmlName = name, JsonName = name.ToJsonId(), ProperName = name.ToProperName(), Index = index }; Context.Add($"{Namespace.Declarations[name.Namespace]}:{name.LocalName}", new JObject { {"@id", $"{name.Namespace.NamespaceName}#{name.LocalName}" }, {"@container", "@index"} }); Context.Add(name.LocalName, new JObject { // {"@id", Namespace.Declarations[name.Namespace] + ":" + name.LocalName}, {"@id", $"{name.Namespace.NamespaceName}#{name.LocalName}" }, {"@container", "@index"} }); try { Context.Add(name.LocalName.ToLowerInvariant(), new JObject { // {"@id", Namespace.Declarations[name.Namespace] + ":" + name.LocalName}, {"@id", $"{name.Namespace.NamespaceName}#{name.LocalName}" }, {"@container", "@index"} }); } catch (Exception e) { Console.WriteLine("AAAG."); } if (index != null) { if (Context.Property(index.LocalName) == null) { Context.Add(index.LocalName, new JObject { {"@id", Namespace.Declarations[index.Namespace] + ":" + index.LocalName}, {"@type", LookupType(index)} }); } } if (!_viaJsonName.ContainsKey(i.JsonName)) { _viaJsonName.Add(i.JsonName, i); } if(!_viaJsonName.ContainsKey(i.ProperName)) { _viaJsonName.Add(i.ProperName, i); } if (!_viaXname.ContainsKey(i.XmlName)) { _viaXname.Add(i.XmlName, i); } } private static string LookupType(XName name) { string type = null; if (name.Namespace == Namespace.Swid) { var element = Schema.Swidtag.XPathSelectElement($@"//xs:attribute[@name=""{name.LocalName}""]", Schema.NamespaceManager); if (element != null) { type = XmlExtensions.GetAttribute(element, "type"); if (type == "xs:anyURI") { type = "@id"; } if (!type.StartsWith("xs:")) { type = "swid:" + type; } } } return type ?? "xs:string"; } private static void AddIdentity(XName name) { var i = new Identity { XmlName = name, JsonName = name.ToJsonId(), ProperName = name.ToProperName(), Index = null }; if (Context.Property(name.LocalName) == null) { string type = null; if (name.Namespace == Namespace.Swid) { var element = Schema.Swidtag.XPathSelectElement($@"//xs:attribute[@name=""{name.LocalName}""]", Schema.NamespaceManager); if (element != null) { type = XmlExtensions.GetAttribute(element, "type"); if (!type.StartsWith("xs:")) { type = "swid:" + type; } } } Context.Add(name.LocalName, new JObject { // {"@id", Namespace.Declarations[name.Namespace] + ":" + name.LocalName}, {"@id", $"{name.Namespace.NamespaceName}#{name.LocalName}" }, {"@type", type ?? "xs:string"} }); Context.Add($"{Namespace.Declarations[name.Namespace]}:{name.LocalName}", new JObject { // {"@id", Namespace.Declarations[name.Namespace] + ":" + name.LocalName}, {"@id", $"{name.Namespace.NamespaceName}#{name.LocalName}" }, {"@type", type ?? "xs:string"} }); } if (!_viaJsonName.ContainsKey(i.JsonName)) { _viaJsonName.Add(i.JsonName, i); } if(!_viaJsonName.ContainsKey(i.ProperName)) { _viaJsonName.Add(i.ProperName, i); } if (!_viaXname.ContainsKey(i.XmlName)) { _viaXname.Add(i.XmlName, i); } } internal class Identity { internal XName Index; internal string JsonName; internal string ProperName; internal XName XmlName; } } }
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace PartsUnlimited.Models.Migrations { public partial class InitialMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: true), NormalizedName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityRole", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Email = table.Column<string>(nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), LockoutEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), Name = table.Column<string>(nullable: true), NormalizedEmail = table.Column<string>(nullable: true), NormalizedUserName = table.Column<string>(nullable: true), PasswordHash = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), SecurityStamp = table.Column<string>(nullable: true), TwoFactorEnabled = table.Column<bool>(nullable: false), UserName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_ApplicationUser", x => x.Id); }); migrationBuilder.CreateTable( name: "Category", columns: table => new { CategoryId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Description = table.Column<string>(nullable: true), ImageUrl = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Category", x => x.CategoryId); }); migrationBuilder.CreateTable( name: "Order", columns: table => new { OrderId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Address = table.Column<string>(nullable: false), City = table.Column<string>(nullable: false), Country = table.Column<string>(nullable: false), Email = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), OrderDate = table.Column<DateTime>(nullable: false), Phone = table.Column<string>(nullable: false), PostalCode = table.Column<string>(nullable: false), Processed = table.Column<bool>(nullable: false), State = table.Column<string>(nullable: false), Total = table.Column<decimal>(nullable: false), Username = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Order", x => x.OrderId); }); migrationBuilder.CreateTable( name: "Store", columns: table => new { StoreId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Store", x => x.StoreId); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityRoleClaim<string>", x => x.Id); table.ForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityUserClaim<string>", x => x.Id); table.ForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityUserLogin<string>", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityUserRole<string>", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Product", columns: table => new { ProductId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), CategoryId = table.Column<int>(nullable: false), Created = table.Column<DateTime>(nullable: false), Description = table.Column<string>(nullable: false), Inventory = table.Column<int>(nullable: false), LeadTime = table.Column<int>(nullable: false), Price = table.Column<decimal>(nullable: false), ProductArtUrl = table.Column<string>(nullable: false), ProductDetails = table.Column<string>(nullable: false), RecommendationId = table.Column<int>(nullable: false), SalePrice = table.Column<decimal>(nullable: false), SkuNumber = table.Column<string>(nullable: false), Title = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Product", x => x.ProductId); table.ForeignKey( name: "FK_Product_Category_CategoryId", column: x => x.CategoryId, principalTable: "Category", principalColumn: "CategoryId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "CartItem", columns: table => new { CartItemId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), CartId = table.Column<string>(nullable: false), Count = table.Column<int>(nullable: false), DateCreated = table.Column<DateTime>(nullable: false), ProductId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_CartItem", x => x.CartItemId); table.ForeignKey( name: "FK_CartItem_Product_ProductId", column: x => x.ProductId, principalTable: "Product", principalColumn: "ProductId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "OrderDetail", columns: table => new { OrderDetailId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), OrderId = table.Column<int>(nullable: false), ProductId = table.Column<int>(nullable: false), Quantity = table.Column<int>(nullable: false), UnitPrice = table.Column<decimal>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_OrderDetail", x => x.OrderDetailId); table.ForeignKey( name: "FK_OrderDetail_Order_OrderId", column: x => x.OrderId, principalTable: "Order", principalColumn: "OrderId", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_OrderDetail_Product_ProductId", column: x => x.ProductId, principalTable: "Product", principalColumn: "ProductId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Raincheck", columns: table => new { RaincheckId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), ProductId = table.Column<int>(nullable: false), Quantity = table.Column<int>(nullable: false), SalePrice = table.Column<double>(nullable: false), StoreId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Raincheck", x => x.RaincheckId); table.ForeignKey( name: "FK_Raincheck_Product_ProductId", column: x => x.ProductId, principalTable: "Product", principalColumn: "ProductId", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Raincheck_Store_StoreId", column: x => x.StoreId, principalTable: "Store", principalColumn: "StoreId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable("AspNetRoleClaims"); migrationBuilder.DropTable("AspNetUserClaims"); migrationBuilder.DropTable("AspNetUserLogins"); migrationBuilder.DropTable("AspNetUserRoles"); migrationBuilder.DropTable("CartItem"); migrationBuilder.DropTable("OrderDetail"); migrationBuilder.DropTable("Raincheck"); migrationBuilder.DropTable("AspNetRoles"); migrationBuilder.DropTable("AspNetUsers"); migrationBuilder.DropTable("Order"); migrationBuilder.DropTable("Product"); migrationBuilder.DropTable("Store"); migrationBuilder.DropTable("Category"); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT namespace NLog.Internal { using System; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; /// <summary> /// Various helper methods for accessing state of ASP application. /// </summary> internal class AspHelper { private AspHelper() { } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("51372ae0-cae7-11cf-be81-00aa00a2fa25")] public interface IObjectContext { // members not important } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("51372af4-cae7-11cf-be81-00aa00a2fa25")] public interface IGetContextProperties { int Count(); object GetProperty(string name); // EnumNames omitted } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("D97A6DA0-A865-11cf-83AF-00A0C90C2BD8")] public interface ISessionObject { string GetSessionID(); object GetValue(string name); void PutValue(string name, object val); int GetTimeout(); void PutTimeout(int t); void Abandon(); int GetCodePage(); void PutCodePage(int cp); int GetLCID(); void PutLCID(); // GetStaticObjects // GetContents } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("D97A6DA0-A866-11cf-83AE-10A0C90C2BD8")] public interface IApplicationObject { object GetValue(string name); void PutValue(string name, object val); // remaining methods removed } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("D97A6DA0-A85D-11cf-83AE-00A0C90C2BD8")] public interface IStringList { object GetItem(object key); int GetCount(); object NewEnum(); } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("D97A6DA0-A85F-11df-83AE-00A0C90C2BD8")] public interface IRequestDictionary { object GetItem(object var); object NewEnum(); int GetCount(); object Key(object varKey); } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("00020400-0000-0000-C000-000000000046")] public interface IDispatch { } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("D97A6DA0-A861-11cf-93AE-00A0C90C2BD8")] public interface IRequest { IDispatch GetItem(string name); IRequestDictionary GetQueryString(); IRequestDictionary GetForm(); IRequestDictionary GetBody(); IRequestDictionary GetServerVariables(); IRequestDictionary GetClientCertificates(); IRequestDictionary GetCookies(); int GetTotalBytes(); void BinaryRead(); // ignored } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("D97A6DA0-A864-11cf-83BE-00A0C90C2BD8")] public interface IResponse { void GetBuffer(); // placeholder void PutBuffer(); // placeholder void GetContentType(); // placeholder void PutContentType(); // placeholder void GetExpires(); // placeholder void PutExpires(); // placeholder void GetExpiresAbsolute(); // placeholder void PutExpiresAbsolute(); // placeholder void GetCookies(); void GetStatus(); void PutStatus(); void Add(); void AddHeader(); void AppendToLog(); // anybody uses this? void BinaryWrite(); void Clear(); void End(); void Flush(); void Redirect(); void Write(object text); // other members omitted } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("71EAF260-0CE0-11D0-A53E-00A0C90C2091")] public interface IReadCookie { void GetItem(object key, out object val); object HasKeys(); void GetNewEnum(); void GetCount(out int count); object GetKey(object key); } static Guid IID_IObjectContext = new Guid("51372ae0-cae7-11cf-be81-00aa00a2fa25"); public static ISessionObject GetSessionObject() { ISessionObject session = null; IObjectContext obj; if (0 == NativeMethods.CoGetObjectContext(ref IID_IObjectContext, out obj)) { IGetContextProperties prop = (IGetContextProperties)obj; if (prop != null) { session = (ISessionObject)prop.GetProperty("Session"); Marshal.ReleaseComObject(prop); } Marshal.ReleaseComObject(obj); } return session; } public static IApplicationObject GetApplicationObject() { IApplicationObject app = null; IObjectContext obj; if (0 == NativeMethods.CoGetObjectContext(ref IID_IObjectContext, out obj)) { IGetContextProperties prop = (IGetContextProperties)obj; if (prop != null) { app = (IApplicationObject)prop.GetProperty("Application"); Marshal.ReleaseComObject(prop); } Marshal.ReleaseComObject(obj); } return app; } public static IRequest GetRequestObject() { IRequest request = null; IObjectContext obj; if (0 == NativeMethods.CoGetObjectContext(ref IID_IObjectContext, out obj)) { IGetContextProperties prop = (IGetContextProperties)obj; if (prop != null) { request = (IRequest)prop.GetProperty("Request"); Marshal.ReleaseComObject(prop); } Marshal.ReleaseComObject(obj); } return request; } public static IResponse GetResponseObject() { IResponse Response = null; IObjectContext obj; if (0 == NativeMethods.CoGetObjectContext(ref IID_IObjectContext, out obj)) { IGetContextProperties prop = (IGetContextProperties)obj; if (prop != null) { Response = (IResponse)prop.GetProperty("Response"); Marshal.ReleaseComObject(prop); } Marshal.ReleaseComObject(obj); } return Response; } public static object GetComDefaultProperty(object o) { if (o == null) return null; return o.GetType().InvokeMember(string.Empty, BindingFlags.GetProperty, null, o, new object[] { }, CultureInfo.InvariantCulture); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AndUInt64() { var test = new SimpleBinaryOpTest__AndUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndUInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<UInt64> _fld1; public Vector256<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AndUInt64 testClass) { var result = Avx2.And(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndUInt64 testClass) { fixed (Vector256<UInt64>* pFld1 = &_fld1) fixed (Vector256<UInt64>* pFld2 = &_fld2) { var result = Avx2.And( Avx.LoadVector256((UInt64*)(pFld1)), Avx.LoadVector256((UInt64*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector256<UInt64> _clsVar1; private static Vector256<UInt64> _clsVar2; private Vector256<UInt64> _fld1; private Vector256<UInt64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AndUInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); } public SimpleBinaryOpTest__AndUInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.And( Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.And( Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.And( Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<UInt64>* pClsVar1 = &_clsVar1) fixed (Vector256<UInt64>* pClsVar2 = &_clsVar2) { var result = Avx2.And( Avx.LoadVector256((UInt64*)(pClsVar1)), Avx.LoadVector256((UInt64*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr); var result = Avx2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr)); var result = Avx2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr)); var result = Avx2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndUInt64(); var result = Avx2.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AndUInt64(); fixed (Vector256<UInt64>* pFld1 = &test._fld1) fixed (Vector256<UInt64>* pFld2 = &test._fld2) { var result = Avx2.And( Avx.LoadVector256((UInt64*)(pFld1)), Avx.LoadVector256((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<UInt64>* pFld1 = &_fld1) fixed (Vector256<UInt64>* pFld2 = &_fld2) { var result = Avx2.And( Avx.LoadVector256((UInt64*)(pFld1)), Avx.LoadVector256((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.And( Avx.LoadVector256((UInt64*)(&test._fld1)), Avx.LoadVector256((UInt64*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<UInt64> op1, Vector256<UInt64> op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((ulong)(left[0] & right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((ulong)(left[i] & right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.And)}<UInt64>(Vector256<UInt64>, Vector256<UInt64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void RoundCurrentDirectionDouble() { var test = new SimpleUnaryOpTest__RoundCurrentDirectionDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__RoundCurrentDirectionDouble { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__RoundCurrentDirectionDouble testClass) { var result = Sse41.RoundCurrentDirection(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundCurrentDirectionDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) { var result = Sse41.RoundCurrentDirection( Sse2.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Vector128<Double> _clsVar1; private Vector128<Double> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundCurrentDirectionDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleUnaryOpTest__RoundCurrentDirectionDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.RoundCurrentDirection( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.RoundCurrentDirection( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.RoundCurrentDirection( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirection), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirection), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundCurrentDirection), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.RoundCurrentDirection( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) { var result = Sse41.RoundCurrentDirection( Sse2.LoadVector128((Double*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var result = Sse41.RoundCurrentDirection(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundCurrentDirection(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundCurrentDirection(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundCurrentDirectionDouble(); var result = Sse41.RoundCurrentDirection(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__RoundCurrentDirectionDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) { var result = Sse41.RoundCurrentDirection( Sse2.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.RoundCurrentDirection(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) { var result = Sse41.RoundCurrentDirection( Sse2.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.RoundCurrentDirection(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.RoundCurrentDirection( Sse2.LoadVector128((Double*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Round(firstOp[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(Math.Round(firstOp[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundCurrentDirection)}<Double>(Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* * Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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.Timers; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace Aurora.Modules.Combat { public class AuroraCombatModule : INonSharedRegionModule, ICombatModule { private readonly List<UUID> CombatAllowedAgents = new List<UUID>(); private readonly Dictionary<string, List<UUID>> Teams = new Dictionary<string, List<UUID>>(); public bool AllowTeamKilling; public bool AllowTeams; public float DamageToTeamKillers; public bool DisallowTeleportingForCombatants = true; public bool ForceRequireCombatPermission = true; public float MaximumDamageToInflict; private float MaximumHealth; public float RegenerateHealthSpeed; public bool SendTeamKillerInfo; public float TeamHitsBeforeSend; public bool m_HasLeftCombat; public Vector3 m_RespawnPosition; public int m_SecondsBeforeRespawn; private IConfig m_config; private bool m_enabled; public bool m_regenHealth; public IScene m_scene; public bool m_shouldRespawn; #region ICombatModule Members public void AddCombatPermission(UUID AgentID) { if (!CombatAllowedAgents.Contains(AgentID)) CombatAllowedAgents.Add(AgentID); } public bool CheckCombatPermission(UUID AgentID) { return CombatAllowedAgents.Contains(AgentID); } public List<UUID> GetTeammates(string Team) { lock (Teams) { List<UUID> Teammates = new List<UUID>(); if (Teams.ContainsKey(Team)) { Teams.TryGetValue(Team, out Teammates); } return Teammates; } } #endregion #region INonSharedRegionModule Members public string Name { get { return "AuroraCombatModule"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { m_config = source.Configs["CombatModule"]; if (m_config != null) { m_enabled = m_config.GetBoolean("Enabled", true); MaximumHealth = m_config.GetFloat("MaximumHealth", 100); ForceRequireCombatPermission = m_config.GetBoolean("ForceRequireCombatPermission", ForceRequireCombatPermission); DisallowTeleportingForCombatants = m_config.GetBoolean("DisallowTeleportingForCombatants", DisallowTeleportingForCombatants); AllowTeamKilling = m_config.GetBoolean("AllowTeamKilling", true); AllowTeams = m_config.GetBoolean("AllowTeams", false); SendTeamKillerInfo = m_config.GetBoolean("SendTeamKillerInfo", false); TeamHitsBeforeSend = m_config.GetFloat("TeamHitsBeforeSend", 3); DamageToTeamKillers = m_config.GetFloat("DamageToTeamKillers", 100); MaximumHealth = m_config.GetFloat("MaximumHealth", 100); MaximumDamageToInflict = m_config.GetFloat("MaximumDamageToInflict", 100); m_RespawnPosition.X = m_config.GetFloat("RespawnPositionX", 128); m_RespawnPosition.Y = m_config.GetFloat("RespawnPositionY", 128); m_RespawnPosition.Z = m_config.GetFloat("RespawnPositionZ", 128); m_SecondsBeforeRespawn = m_config.GetInt("SecondsBeforeRespawn", 5); m_shouldRespawn = m_config.GetBoolean("ShouldRespawn", false); m_regenHealth = m_config.GetBoolean("RegenerateHealth", true); RegenerateHealthSpeed = m_config.GetFloat("RegenerateHealthSpeed", 0.0625f); } } public void Close() { } public void AddRegion(IScene scene) { if (m_enabled) { m_scene = scene; scene.RegisterModuleInterface<ICombatModule>(this); scene.EventManager.OnNewPresence += NewPresence; scene.EventManager.OnRemovePresence += EventManager_OnRemovePresence; scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel; scene.Permissions.OnAllowedOutgoingLocalTeleport += AllowedTeleports; scene.Permissions.OnAllowedOutgoingRemoteTeleport += AllowedTeleports; scene.EventManager.OnLandObjectAdded += OnLandObjectAdded; } } public void RemoveRegion(IScene scene) { if (m_enabled) { scene.EventManager.OnNewPresence -= NewPresence; scene.EventManager.OnRemovePresence -= EventManager_OnRemovePresence; scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel; scene.Permissions.OnAllowedOutgoingLocalTeleport -= AllowedTeleports; scene.Permissions.OnAllowedOutgoingRemoteTeleport -= AllowedTeleports; scene.EventManager.OnLandObjectAdded -= OnLandObjectAdded; } } public void RegionLoaded(IScene scene) { } #endregion private bool AllowedTeleports(UUID userID, IScene scene, out string reason) { //Make sure that agents that are in combat cannot tp around. They CAN tp if they are out of combat however reason = ""; IScenePresence SP = null; if (scene.TryGetScenePresence(userID, out SP)) if (DisallowTeleportingForCombatants && SP.RequestModuleInterface<ICombatPresence>() != null && !SP.RequestModuleInterface<ICombatPresence>().HasLeftCombat && !SP.Invulnerable) return false; return true; } private void NewPresence(IScenePresence presence) { presence.RegisterModuleInterface<ICombatPresence>(new CombatPresence(this, presence, m_config)); } private void EventManager_OnRemovePresence(IScenePresence presence) { CombatPresence m = (CombatPresence) presence.RequestModuleInterface<ICombatPresence>(); if (m != null) { presence.UnregisterModuleInterface<ICombatPresence>(m); m.Close(); } } public void AddPlayerToTeam(string Team, UUID AgentID) { lock (Teams) { List<UUID> Teammates = new List<UUID>(); if (Teams.TryGetValue(Team, out Teammates)) Teams.Remove(Team); else Teammates = new List<UUID>(); Teammates.Add(AgentID); Teams.Add(Team, Teammates); } } public void RemovePlayerFromTeam(string Team, UUID AgentID) { lock (Teams) { List<UUID> Teammates = new List<UUID>(); if (Teams.TryGetValue(Team, out Teammates)) { Teams.Remove(Team); if (Teammates.Contains(AgentID)) Teammates.Remove(AgentID); Teams.Add(Team, Teammates); } } } private void OnLandObjectAdded(LandData newParcel) { //If a new land object is added or updated, we need to redo the check for the avatars invulnerability #if (!ISWIN) m_scene.ForEachScenePresence(delegate(IScenePresence sp) { AvatarEnteringParcel(sp, null); }); #else m_scene.ForEachScenePresence(sp => AvatarEnteringParcel(sp, null)); #endif } public void AddDamageToPrim(ISceneEntity entity) { } private void AvatarEnteringParcel(IScenePresence avatar, ILandObject oldParcel) { ILandObject obj = null; IParcelManagementModule parcelManagement = avatar.Scene.RequestModuleInterface<IParcelManagementModule>(); if (parcelManagement != null) { obj = parcelManagement.GetLandObject(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); } if (obj == null) return; try { if ((obj.LandData.Flags & (uint) ParcelFlags.AllowDamage) != 0) { ICombatPresence CP = avatar.RequestModuleInterface<ICombatPresence>(); CP.Health = MaximumHealth; avatar.Invulnerable = false; } else { avatar.Invulnerable = true; } } catch (Exception) { } } #region Nested type: CombatObject private class CombatObject //: ICombatPresence { private readonly float MaximumDamageToInflict; private readonly float MaximumHealth; private readonly AuroraCombatModule m_combatModule; private readonly ISceneEntity m_part; private string m_Team; private float m_health = 100f; public CombatObject(AuroraCombatModule module, ISceneEntity part, IConfig m_config) { m_part = part; m_combatModule = module; MaximumHealth = m_config.GetFloat("MaximumHealth", 100); MaximumDamageToInflict = m_config.GetFloat("MaximumDamageToInflict", 100); m_Team = "No Team"; m_part.RootChild.OnAddPhysics += AddPhysics; m_part.RootChild.OnRemovePhysics += RemovePhysics; } public string Team { get { return m_Team; } set { m_combatModule.RemovePlayerFromTeam(m_Team, m_part.UUID); m_Team = value; m_combatModule.AddPlayerToTeam(m_Team, m_part.UUID); } } public float Health { get { return m_health; } set { m_health = value; } } public bool HasLeftCombat { get { return false; } set { } } public void RemovePhysics() { if (m_part.RootChild.PhysActor != null) m_part.RootChild.PhysActor.OnCollisionUpdate -= PhysicsActor_OnCollisionUpdate; } public void AddPhysics() { if (m_part.RootChild.PhysActor != null) m_part.RootChild.PhysActor.OnCollisionUpdate += PhysicsActor_OnCollisionUpdate; } public void PhysicsActor_OnCollisionUpdate(EventArgs e) { /*if (HasLeftCombat) return; */ if (e == null) return; CollisionEventUpdate collisionData = (CollisionEventUpdate) e; /*Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList; UUID killerObj = UUID.Zero; foreach (uint localid in coldata.Keys) { ISceneChildEntity part = m_part.Scene.GetSceneObjectPart(localid); if (part != null && part.ParentEntity.Damage != -1.0f) { if (part.ParentEntity.Damage > MaximumDamageToInflict) part.ParentEntity.Damage = MaximumDamageToInflict; Health -= part.ParentEntity.Damage; if (Health <= 0.0f) killerObj = part.UUID; } else { float Z = Math.Abs(m_part.Velocity.Z); if (coldata[localid].PenetrationDepth >= 0.05f) Health -= coldata[localid].PenetrationDepth*Z; } //Regenerate health (this is approx 1 sec) if ((int) (Health + 0.0625) <= m_combatModule.MaximumHealth) Health += 0.0625f; if (Health > m_combatModule.MaximumHealth) Health = m_combatModule.MaximumHealth; } if (Health <= 0) { Die(killerObj); }*/ } public void LeaveCombat() { //NoOp } public void JoinCombat() { //NoOp } public List<UUID> GetTeammates() { return m_combatModule.GetTeammates(m_Team); } public void IncurDamage(uint localID, double damage, UUID OwnerID) { if (damage < 0) return; if (damage > MaximumDamageToInflict) damage = MaximumDamageToInflict; float health = Health; health -= (float) damage; if (health <= 0) Die(OwnerID); } public void IncurDamage(uint localID, double damage, string RegionName, Vector3 pos, Vector3 lookat, UUID OwnerID) { if (damage < 0) return; if (damage > MaximumDamageToInflict) damage = MaximumDamageToInflict; float health = Health; health -= (float) damage; if (health <= 0) Die(OwnerID); } public void IncurHealing(double healing, UUID OwnerID) { if (healing < 0) return; float health = Health; health += (float) healing; if (health >= MaximumHealth) health = MaximumHealth; } private void Die(UUID OwnerID) { foreach (IScriptModule m in m_part.Scene.RequestModuleInterfaces<IScriptModule>()) { m.PostObjectEvent(m_part.UUID, "dead_object", new object[] {OwnerID}); } } public void SetStat(string StatName, float statValue) { } } #endregion #region Nested type: CombatPresence private class CombatPresence : ICombatPresence { #region Declares private readonly Dictionary<UUID, float> TeamHits = new Dictionary<UUID, float>(); private readonly Timer m_healthtimer = new Timer(); private IScenePresence m_SP; private string m_Team = "No Team"; private AuroraCombatModule m_combatModule; private float m_health = 100f; //private Dictionary<string, float> GenericStats = new Dictionary<string, float>(); public float Health { get { return m_health; } set { if (value > m_health) IncurHealing(value - m_health); else IncurDamage(null, m_health - value); } } public bool HasLeftCombat { get { return m_combatModule.m_HasLeftCombat; } set { m_combatModule.m_HasLeftCombat = value; } } public string Team { get { return m_Team; } set { m_combatModule.RemovePlayerFromTeam(m_Team, m_SP.UUID); m_Team = value; m_combatModule.AddPlayerToTeam(m_Team, m_SP.UUID); } } #endregion #region Initialization/Close public CombatPresence(AuroraCombatModule module, IScenePresence SP, IConfig m_config) { m_SP = SP; m_combatModule = module; HasLeftCombat = false; m_Team = "No Team"; SP.OnAddPhysics += SP_OnAddPhysics; SP.OnRemovePhysics += SP_OnRemovePhysics; //Use this to fix the avatars health m_healthtimer.Interval = 1000; // 1 sec m_healthtimer.Elapsed += fixAvatarHealth_Elapsed; m_healthtimer.Start(); } public void Close() { m_healthtimer.Stop(); m_healthtimer.Close(); m_SP.OnAddPhysics -= SP_OnAddPhysics; m_SP.OnRemovePhysics -= SP_OnRemovePhysics; SP_OnRemovePhysics(); m_combatModule = null; m_SP = null; } #endregion #region Physics events public void SP_OnRemovePhysics() { if (m_SP.PhysicsActor != null) m_SP.PhysicsActor.OnCollisionUpdate -= PhysicsActor_OnCollisionUpdate; } public void SP_OnAddPhysics() { if (m_SP.PhysicsActor != null) m_SP.PhysicsActor.OnCollisionUpdate += PhysicsActor_OnCollisionUpdate; } public void PhysicsActor_OnCollisionUpdate(EventArgs e) { if (m_SP == null || m_SP.Scene == null || m_SP.Invulnerable || HasLeftCombat || e == null) return; CollisionEventUpdate collisionData = (CollisionEventUpdate) e; Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList; float starthealth = Health; IScenePresence killingAvatar = null; foreach (uint localid in coldata.Keys) { ISceneChildEntity part = m_SP.Scene.GetSceneObjectPart(localid); IScenePresence otherAvatar = null; if (part != null && part.ParentEntity.Damage > 0) { otherAvatar = m_SP.Scene.GetScenePresence(part.OwnerID); ICombatPresence OtherAvatarCP = otherAvatar == null ? null : otherAvatar.RequestModuleInterface<ICombatPresence>(); if (OtherAvatarCP != null && OtherAvatarCP.HasLeftCombat) // If the avatar is null, the person is not inworld, and not on a team //If they have left combat, do not let them cause any damage. continue; //Check max damage to inflict if (part.ParentEntity.Damage > m_combatModule.MaximumDamageToInflict) part.ParentEntity.Damage = m_combatModule.MaximumDamageToInflict; // If the avatar is null, the person is not inworld, and not on a team if (m_combatModule.AllowTeams && OtherAvatarCP != null && otherAvatar.UUID != m_SP.UUID && OtherAvatarCP.Team == Team) { float Hits = 0; if (!TeamHits.TryGetValue(otherAvatar.UUID, out Hits)) Hits = 0; Hits++; if (m_combatModule.SendTeamKillerInfo && Hits == m_combatModule.TeamHitsBeforeSend) { otherAvatar.ControllingClient.SendAlertMessage("You have shot too many teammates and " + m_combatModule.DamageToTeamKillers + " health has been taken from you!"); OtherAvatarCP.IncurDamage(null, m_combatModule.DamageToTeamKillers); Hits = 0; } TeamHits[otherAvatar.UUID] = Hits; if (m_combatModule.AllowTeamKilling) //Green light on team killing Health -= part.ParentEntity.Damage; } else //Object, hit em Health -= part.ParentEntity.Damage; } else { float Z = m_SP.Velocity.Length()/20; if (coldata[localid].PenetrationDepth >= 0.05f && m_SP.Velocity.Z < -5 && !m_SP.PhysicsActor.Flying) { Z = Math.Min(Z, 1.5f); float damage = Math.Min(coldata[localid].PenetrationDepth, 15f); Health -= damage*Z; } } if (Health > m_combatModule.MaximumHealth) Health = m_combatModule.MaximumHealth; if (Health <= 0 && killingAvatar == null) killingAvatar = otherAvatar; //MainConsole.Instance.Debug("[AVATAR]: Collision with localid: " + localid.ToString() + " at depth: " + coldata[localid].ToString()); } if (starthealth != Health) m_SP.ControllingClient.SendHealth(Health); if (Health <= 0) KillAvatar(killingAvatar, "You killed " + m_SP.Name, "You died!", true, true); } #endregion #region Kill Avatar public void KillAvatar(IScenePresence killingAvatar, string killingAvatarMessage, string deadAvatarMessage, bool TeleportAgent, bool showAgentMessages) { try { if (showAgentMessages) { if (deadAvatarMessage != "") m_SP.ControllingClient.SendAgentAlertMessage(deadAvatarMessage, true); //Send it as a blue box at the bottom of the screen rather than as a full popup if (killingAvatar != null && killingAvatarMessage != "") killingAvatar.ControllingClient.SendAlertMessage(killingAvatarMessage); } } catch (InvalidOperationException) { } Health = m_combatModule.MaximumHealth; if (TeleportAgent) { if (m_combatModule.m_shouldRespawn) { if (m_combatModule.m_SecondsBeforeRespawn != 0) { m_SP.AllowMovement = false; this.HasLeftCombat = true; Timer t = new Timer {Interval = m_combatModule.m_SecondsBeforeRespawn*1000, AutoReset = false}; //Use this to reenable movement and combat //Only once t.Elapsed += respawn_Elapsed; t.Start(); } m_SP.Teleport(m_combatModule.m_RespawnPosition); } else { IEntityTransferModule transferModule = m_SP.Scene.RequestModuleInterface<IEntityTransferModule>(); if (transferModule != null) if (!transferModule.TeleportHome(m_SP.UUID, m_SP.ControllingClient)) { if (m_SP.PhysicsActor != null) m_SP.PhysicsActor.Flying = true; m_SP.Teleport(new Vector3(m_SP.Scene.RegionInfo.RegionSizeX/2, m_SP.Scene.RegionInfo.RegionSizeY/2, 128)); } } } m_SP.Scene.AuroraEventManager.FireGenericEventHandler("OnAvatarDeath", m_SP); } #endregion #region Timer events private void fixAvatarHealth_Elapsed(object sender, ElapsedEventArgs e) { //Regenerate health a bit every second if (m_combatModule.m_regenHealth) { if ((Health + m_combatModule.RegenerateHealthSpeed) <= m_combatModule.MaximumHealth) { m_health += m_combatModule.RegenerateHealthSpeed; m_SP.ControllingClient.SendHealth(Health); } else if (Health != m_combatModule.MaximumHealth) { m_health = m_combatModule.MaximumHealth; m_SP.ControllingClient.SendHealth(Health); } } } private void respawn_Elapsed(object sender, ElapsedEventArgs e) { m_SP.AllowMovement = true; this.HasLeftCombat = false; } #endregion #region Combat functions public void LeaveCombat() { m_combatModule.RemovePlayerFromTeam(m_Team, m_SP.UUID); HasLeftCombat = true; } public void JoinCombat() { HasLeftCombat = false; m_combatModule.AddPlayerToTeam(m_Team, m_SP.UUID); } public List<UUID> GetTeammates() { return m_combatModule.GetTeammates(m_Team); } #endregion #region Incur* functions public void IncurDamage(IScenePresence killingAvatar, double damage) { InnerIncurDamage(killingAvatar, damage, true); } public void IncurDamage(IScenePresence killingAvatar, double damage, string RegionName, Vector3 pos, Vector3 lookat) { if (damage < 0) return; if (InnerIncurDamage(killingAvatar, damage, false)) { //They died, teleport them IEntityTransferModule entityTransfer = m_SP.Scene.RequestModuleInterface<IEntityTransferModule>(); if (entityTransfer != null) entityTransfer.RequestTeleportLocation(m_SP.ControllingClient, RegionName, pos, lookat, (uint) TeleportFlags.ViaHome); } } public void IncurHealing(double healing) { if (healing < 0) return; if (!this.HasLeftCombat || !m_combatModule.ForceRequireCombatPermission) { m_health += (float) healing; if (m_health >= m_combatModule.MaximumHealth) m_health = m_combatModule.MaximumHealth; m_SP.ControllingClient.SendHealth(m_health); } } private bool InnerIncurDamage(IScenePresence killingAvatar, double damage, bool teleport) { if (damage < 0) return false; if (!this.HasLeftCombat || !m_combatModule.ForceRequireCombatPermission) { if (damage > m_combatModule.MaximumDamageToInflict) damage = m_combatModule.MaximumDamageToInflict; m_health -= (float) damage; m_SP.ControllingClient.SendHealth(Health); if (Health <= 0) { KillAvatar(killingAvatar, "You killed " + m_SP.Name, "You died!", teleport, true); return true; } } return false; } #endregion #region Stat functions public void SetStat(string StatName, float statValue) { } #endregion } #endregion } }
namespace eidss.main.Login { public partial class ChangePasswordForm { //Inherits System.Windows.Forms.Form //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool disposing) { try { if (disposing && components != null) { components.Dispose(); } } finally { base.Dispose(disposing); } } //Required by the Windows Form Designer private System.ComponentModel.Container components = null; //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.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ChangePasswordForm)); this.lbPassword2 = new System.Windows.Forms.Label(); this.txtNewPassword2 = new DevExpress.XtraEditors.TextEdit(); this.lbPassword1 = new System.Windows.Forms.Label(); this.txtNewPassword1 = new DevExpress.XtraEditors.TextEdit(); this.lbOrganization = new System.Windows.Forms.Label(); this.lbUserName = new System.Windows.Forms.Label(); this.txtOrganization = new DevExpress.XtraEditors.TextEdit(); this.txtUserName = new DevExpress.XtraEditors.TextEdit(); this.lbPassword = new System.Windows.Forms.Label(); this.txtPassword = new DevExpress.XtraEditors.TextEdit(); this.btnOk = new DevExpress.XtraEditors.SimpleButton(); this.btnCancel = new DevExpress.XtraEditors.SimpleButton(); this.lbCurrPassLng = new DevExpress.XtraEditors.LabelControl(); this.lbLoginLng = new DevExpress.XtraEditors.LabelControl(); this.lbConfNewPassLng = new DevExpress.XtraEditors.LabelControl(); this.lbNewPassLng = new DevExpress.XtraEditors.LabelControl(); ((System.ComponentModel.ISupportInitialize)(this.txtNewPassword2.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtNewPassword1.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtOrganization.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtUserName.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtPassword.Properties)).BeginInit(); this.SuspendLayout(); // // lbPassword2 // resources.ApplyResources(this.lbPassword2, "lbPassword2"); this.lbPassword2.Name = "lbPassword2"; // // txtNewPassword2 // resources.ApplyResources(this.txtNewPassword2, "txtNewPassword2"); this.txtNewPassword2.Name = "txtNewPassword2"; this.txtNewPassword2.Properties.PasswordChar = '*'; this.txtNewPassword2.Tag = "{M}"; this.txtNewPassword2.Enter += new System.EventHandler(this.Control_Enter); this.txtNewPassword2.Leave += new System.EventHandler(this.Control_Leave); // // lbPassword1 // resources.ApplyResources(this.lbPassword1, "lbPassword1"); this.lbPassword1.Name = "lbPassword1"; // // txtNewPassword1 // resources.ApplyResources(this.txtNewPassword1, "txtNewPassword1"); this.txtNewPassword1.Name = "txtNewPassword1"; this.txtNewPassword1.Properties.PasswordChar = '*'; this.txtNewPassword1.Tag = "{M}"; this.txtNewPassword1.Enter += new System.EventHandler(this.Control_Enter); this.txtNewPassword1.Leave += new System.EventHandler(this.Control_Leave); // // lbOrganization // resources.ApplyResources(this.lbOrganization, "lbOrganization"); this.lbOrganization.Name = "lbOrganization"; // // lbUserName // resources.ApplyResources(this.lbUserName, "lbUserName"); this.lbUserName.Name = "lbUserName"; // // txtOrganization // resources.ApplyResources(this.txtOrganization, "txtOrganization"); this.txtOrganization.Name = "txtOrganization"; this.txtOrganization.Tag = "{M}"; // // txtUserName // resources.ApplyResources(this.txtUserName, "txtUserName"); this.txtUserName.Name = "txtUserName"; this.txtUserName.Tag = "{M}"; this.txtUserName.Enter += new System.EventHandler(this.Control_Enter); this.txtUserName.Leave += new System.EventHandler(this.Control_Leave); // // lbPassword // resources.ApplyResources(this.lbPassword, "lbPassword"); this.lbPassword.Name = "lbPassword"; // // txtPassword // resources.ApplyResources(this.txtPassword, "txtPassword"); this.txtPassword.Name = "txtPassword"; this.txtPassword.Properties.PasswordChar = '*'; this.txtPassword.Tag = "{M}"; this.txtPassword.Enter += new System.EventHandler(this.Control_Enter); this.txtPassword.Leave += new System.EventHandler(this.Control_Leave); // // btnOk // resources.ApplyResources(this.btnOk, "btnOk"); this.btnOk.Name = "btnOk"; this.btnOk.Click += new System.EventHandler(this.btnOk_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Name = "btnCancel"; // // lbCurrPassLng // this.lbCurrPassLng.Appearance.BackColor = ((System.Drawing.Color)(resources.GetObject("lbCurrPassLng.Appearance.BackColor"))); this.lbCurrPassLng.Appearance.ForeColor = ((System.Drawing.Color)(resources.GetObject("lbCurrPassLng.Appearance.ForeColor"))); this.lbCurrPassLng.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; resources.ApplyResources(this.lbCurrPassLng, "lbCurrPassLng"); this.lbCurrPassLng.Name = "lbCurrPassLng"; // // lbLoginLng // this.lbLoginLng.Appearance.BackColor = ((System.Drawing.Color)(resources.GetObject("lbLoginLng.Appearance.BackColor"))); this.lbLoginLng.Appearance.ForeColor = ((System.Drawing.Color)(resources.GetObject("lbLoginLng.Appearance.ForeColor"))); this.lbLoginLng.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; resources.ApplyResources(this.lbLoginLng, "lbLoginLng"); this.lbLoginLng.Name = "lbLoginLng"; // // lbConfNewPassLng // this.lbConfNewPassLng.Appearance.BackColor = ((System.Drawing.Color)(resources.GetObject("lbConfNewPassLng.Appearance.BackColor"))); this.lbConfNewPassLng.Appearance.ForeColor = ((System.Drawing.Color)(resources.GetObject("lbConfNewPassLng.Appearance.ForeColor"))); this.lbConfNewPassLng.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; resources.ApplyResources(this.lbConfNewPassLng, "lbConfNewPassLng"); this.lbConfNewPassLng.Name = "lbConfNewPassLng"; // // lbNewPassLng // this.lbNewPassLng.Appearance.BackColor = ((System.Drawing.Color)(resources.GetObject("lbNewPassLng.Appearance.BackColor"))); this.lbNewPassLng.Appearance.ForeColor = ((System.Drawing.Color)(resources.GetObject("lbNewPassLng.Appearance.ForeColor"))); this.lbNewPassLng.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; resources.ApplyResources(this.lbNewPassLng, "lbNewPassLng"); this.lbNewPassLng.Name = "lbNewPassLng"; // // ChangePasswordForm // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.lbConfNewPassLng); this.Controls.Add(this.lbNewPassLng); this.Controls.Add(this.lbCurrPassLng); this.Controls.Add(this.lbLoginLng); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOk); this.Controls.Add(this.lbPassword1); this.Controls.Add(this.lbOrganization); this.Controls.Add(this.lbUserName); this.Controls.Add(this.txtOrganization); this.Controls.Add(this.txtUserName); this.Controls.Add(this.txtPassword); this.Controls.Add(this.txtNewPassword1); this.Controls.Add(this.txtNewPassword2); this.Controls.Add(this.lbPassword2); this.Controls.Add(this.lbPassword); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.HelpTopicId = "Changing_Password"; this.MaximizeBox = false; this.Name = "ChangePasswordForm"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; ((System.ComponentModel.ISupportInitialize)(this.txtNewPassword2.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtNewPassword1.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtOrganization.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtUserName.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtPassword.Properties)).EndInit(); this.ResumeLayout(false); } internal System.Windows.Forms.Label lbPassword2; internal DevExpress.XtraEditors.TextEdit txtNewPassword2; internal System.Windows.Forms.Label lbPassword1; internal DevExpress.XtraEditors.TextEdit txtNewPassword1; internal System.Windows.Forms.Label lbOrganization; internal System.Windows.Forms.Label lbUserName; protected internal DevExpress.XtraEditors.TextEdit txtOrganization; protected internal DevExpress.XtraEditors.TextEdit txtUserName; internal System.Windows.Forms.Label lbPassword; internal DevExpress.XtraEditors.TextEdit txtPassword; internal DevExpress.XtraEditors.SimpleButton btnOk; internal DevExpress.XtraEditors.SimpleButton btnCancel; internal DevExpress.XtraEditors.LabelControl lbCurrPassLng; internal DevExpress.XtraEditors.LabelControl lbLoginLng; internal DevExpress.XtraEditors.LabelControl lbConfNewPassLng; internal DevExpress.XtraEditors.LabelControl lbNewPassLng; } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.IO; using System.Text; namespace fyiReporting.RdlDesktop { class FileReadCache { Hashtable files; // hashtable of file names and contents int maxFiles; // maximum number of files allowed in cache int cachehits; int cacherequests; int maxSize; // maximum size of a file allowed in cache public FileReadCache (int maxCount, int maxEntrySize) { maxFiles = maxCount; maxSize = maxEntrySize; files = new Hashtable(); cachehits = 0; cacherequests = 0; } public byte[] Read(string file) { CacheReadEntry ce=null; lock (this) { cacherequests++; ce = (CacheReadEntry) files[file]; if (ce == null) { // entry isn't found; create new one if (files.Count >= maxFiles) // Exceeded cache count? Reduce(); // yes, we need to reduce the file count FileStream fs = null; BinaryReader reader = null; byte[] bytes; try { fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read); reader = new BinaryReader(fs); bytes = new byte[fs.Length]; int read; int totalRead=0; while((read = reader.Read(bytes, 0, bytes.Length)) != 0) { totalRead += read; } ce = new CacheReadEntry(file, bytes); if (bytes.Length <= this.maxSize) files.Add(file, ce); // don't actually cache if too big } catch (Exception e) { Console.WriteLine("File read error: {0} ", e ); throw e; } finally { if (reader != null) reader.Close(); if (fs != null) fs.Close(); } } else { ce.Timestamp = DateTime.Now; cachehits++; } } if (ce != null) return ce.Value; else return null; } public string ReadString(string file) { byte[] bytes = this.Read(file); return Encoding.ASCII.GetString(bytes); } public int CacheHits { get { return cachehits; } set { cachehits = value; } } public int Count { get { return files.Count; } } // Clear out the files based on when they were last referenced. Caller passes // the timespan they want to retain. Anything older gets tossed. public int Clear(TimeSpan ts) { int numClearedFiles=0; lock (this) { DateTime ctime = DateTime.Now - ts; // anything older than this is deleted // Build list of entries to be deleted ArrayList f = new ArrayList(); foreach (CacheReadEntry ce in files.Values) { if (ce.Timestamp < ctime) f.Add(ce); } // Now delete them from the File hash foreach (CacheReadEntry ce in f) { files.Remove(ce.File); } numClearedFiles = f.Count; } return numClearedFiles; } // Clear out all the cached files. public int ClearAll() { int numClearedFiles; lock (this) { // restart the cache numClearedFiles = files.Count; files = new Hashtable(); cachehits=0; cacherequests=0; } return numClearedFiles; } // Reduce the number of entries in the list. We're about to exceed our size. private int Reduce() { // Build list of entries to be deleted ArrayList f = new ArrayList(files.Values); f.Sort(); // comparer sorts by last reference time // Now delete them from the File hash int max = (int) (maxFiles / 4); foreach (CacheReadEntry ce in f) { files.Remove(ce.File); max--; if (max <= 0) break; } return max; } } class CacheReadEntry : IComparable { string _File; byte[] _Value; DateTime _Timestamp; DateTime _CreatedTime; // time cache entry created public CacheReadEntry(string file, byte[] ba) { _File = file; _CreatedTime = _Timestamp = DateTime.Now; _Value = ba; } public string File { get { return _File; } } public byte[] Value { get { return _Value; } } public DateTime CreatedTime { get { return _CreatedTime; } } public DateTime Timestamp { get { return _Timestamp; } set { _Timestamp = value; } } #region IComparable Members public int CompareTo(object obj) { CacheReadEntry ce = obj as CacheReadEntry; long t = this.Timestamp.Ticks - ce.Timestamp.Ticks; if (t < 0) return -1; else if (t > 0) return 1; return 0; } #endregion } }
// <copyright file="VectorTests.Arithmetic.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 Math.NET // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.LinearAlgebra; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex { #if NOSYSNUMERICS using Complex = Numerics.Complex; #else using Complex = System.Numerics.Complex; #endif /// <summary> /// Abstract class with the common arithmetic set of vector tests. /// </summary> public abstract partial class VectorTests { /// <summary> /// Can call unary "+" operator. /// </summary> [Test] public void CanCallUnaryPlusOperator() { var vector = CreateVector(Data); var other = +vector; CollectionAssert.AreEqual(vector, other); } /// <summary> /// Can add a scalar to a vector. /// </summary> [Test] public void CanAddScalarToVector() { var copy = CreateVector(Data); var vector = copy.Add(2.0); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] + 2.0, vector[i]); } vector.Add(0.0); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] + 2.0, vector[i]); } } /// <summary> /// Can add a scalar to a vector using result vector. /// </summary> [Test] public void CanAddScalarToVectorIntoResultVector() { var vector = CreateVector(Data); var result = CreateVector(Data.Length); vector.Add(2.0, result); CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] + 2.0, result[i]); } vector.Add(0.0, result); CollectionAssert.AreEqual(Data, result); } /// <summary> /// Adding scalar to a vector using result vector with wrong size throws an exception. /// </summary> [Test] public void AddingScalarWithWrongSizeResultVectorThrowsArgumentException() { var vector = CreateVector(Data.Length); var result = CreateVector(Data.Length + 1); Assert.That(() => vector.Add(0.0, result), Throws.ArgumentException); } /// <summary> /// Adding two vectors of different size throws an exception. /// </summary> [Test] public void AddingTwoVectorsOfDifferentSizeThrowsArgumentException() { var vector = CreateVector(Data.Length); var other = CreateVector(Data.Length + 1); Assert.That(() => vector.Add(other), Throws.ArgumentException); } /// <summary> /// Adding two vectors when a result vector is different size throws an exception. /// </summary> [Test] public void AddingTwoVectorsAndResultIsDifferentSizeThrowsArgumentException() { var vector = CreateVector(Data.Length); var other = CreateVector(Data.Length); var result = CreateVector(Data.Length + 1); Assert.That(() => vector.Add(other, result), Throws.ArgumentException); } /// <summary> /// Addition operator throws <c>ArgumentException</c> if vectors are different size. /// </summary> [Test] public void AdditionOperatorIfVectorsAreDifferentSizeThrowsArgumentException() { var a = CreateVector(Data.Length); var b = CreateVector(Data.Length + 1); Assert.That(() => a += b, Throws.ArgumentException); } /// <summary> /// Can add two vectors. /// </summary> [Test] public void CanAddTwoVectors() { var copy = CreateVector(Data); var other = CreateVector(Data); var vector = copy.Add(other); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] * 2.0, vector[i]); } } /// <summary> /// Can add two vectors using a result vector. /// </summary> [Test] public void CanAddTwoVectorsIntoResultVector() { var vector = CreateVector(Data); var other = CreateVector(Data); var result = CreateVector(Data.Length); vector.Add(other, result); CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified."); CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] * 2.0, result[i]); } } /// <summary> /// Can add two vectors using "+" operator. /// </summary> [Test] public void CanAddTwoVectorsUsingOperator() { var vector = CreateVector(Data); var other = CreateVector(Data); var result = vector + other; CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified."); CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] * 2.0, result[i]); } } /// <summary> /// Can add a vector to itself. /// </summary> [Test] public void CanAddVectorToItself() { var copy = CreateVector(Data); var vector = copy.Add(copy); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] * 2.0, vector[i]); } } /// <summary> /// Can add a vector to itself using a result vector. /// </summary> [Test] public void CanAddVectorToItselfIntoResultVector() { var vector = CreateVector(Data); var result = CreateVector(Data.Length); vector.Add(vector, result); CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] * 2.0, result[i]); } } /// <summary> /// Can add a vector to itself as result vector. /// </summary> [Test] public void CanAddTwoVectorsUsingItselfAsResultVector() { var vector = CreateVector(Data); var other = CreateVector(Data); vector.Add(other, vector); CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] * 2.0, vector[i]); } } /// <summary> /// Can negate a vector. /// </summary> [Test] public void CanCallNegate() { var vector = CreateVector(Data); var other = vector.Negate(); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(-Data[i], other[i]); } } /// <summary> /// Can call unary negation operator. /// </summary> [Test] public void CanCallUnaryNegationOperator() { var vector = CreateVector(Data); var other = -vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(-Data[i], other[i]); } } /// <summary> /// Can subtract a scalar from a vector. /// </summary> [Test] public void CanSubtractScalarFromVector() { var copy = CreateVector(Data); var vector = copy.Subtract(2.0); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] - 2.0, vector[i]); } vector.Subtract(0.0); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] - 2.0, vector[i]); } } /// <summary> /// Can subtract a scalar from a vector using a result vector. /// </summary> [Test] public void CanSubtractScalarFromVectorIntoResultVector() { var vector = CreateVector(Data); var result = CreateVector(Data.Length); vector.Subtract(2.0, result); CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i], vector[i], "Making sure the original vector wasn't modified."); Assert.AreEqual(Data[i] - 2.0, result[i]); } vector.Subtract(0.0, result); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i], result[i]); } } /// <summary> /// Subtracting a scalar with wrong size result vector throws <c>ArgumentException</c>. /// </summary> [Test] public void SubtractingScalarWithWrongSizeResultVectorThrowsArgumentException() { var vector = CreateVector(Data.Length); var result = CreateVector(Data.Length + 1); Assert.That(() => vector.Subtract(0.0, result), Throws.ArgumentException); } /// <summary> /// Subtracting two vectors of differing size throws <c>ArgumentException</c>. /// </summary> [Test] public void SubtractingTwoVectorsOfDifferingSizeThrowsArgumentException() { var vector = CreateVector(Data.Length); var other = CreateVector(Data.Length + 1); Assert.That(() => vector.Subtract(other), Throws.ArgumentException); } /// <summary> /// Subtracting two vectors when a result vector is different size throws <c>ArgumentException</c>. /// </summary> [Test] public void SubtractingTwoVectorsAndResultIsDifferentSizeThrowsArgumentException() { var vector = CreateVector(Data.Length); var other = CreateVector(Data.Length); var result = CreateVector(Data.Length + 1); Assert.That(() => vector.Subtract(other, result), Throws.ArgumentException); } /// <summary> /// Subtraction operator throws <c>ArgumentException</c> if vectors are different size. /// </summary> [Test] public void SubtractionOperatorIfVectorsAreDifferentSizeThrowsArgumentException() { var a = CreateVector(Data.Length); var b = CreateVector(Data.Length + 1); Assert.That(() => a -= b, Throws.ArgumentException); } /// <summary> /// Can subtract two vectors. /// </summary> [Test] public void CanSubtractTwoVectors() { var copy = CreateVector(Data); var other = CreateVector(Data); var vector = copy.Subtract(other); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Complex.Zero, vector[i]); } } /// <summary> /// Can subtract two vectors using a result vector. /// </summary> [Test] public void CanSubtractTwoVectorsIntoResultVector() { var vector = CreateVector(Data); var other = CreateVector(Data); var result = CreateVector(Data.Length); vector.Subtract(other, result); CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified."); CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Complex.Zero, result[i]); } } /// <summary> /// Can subtract two vectors using "-" operator. /// </summary> [Test] public void CanSubtractTwoVectorsUsingOperator() { var vector = CreateVector(Data); var other = CreateVector(Data); var result = vector - other; CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified."); CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Complex.Zero, result[i]); } } /// <summary> /// Can subtract a vector from itself. /// </summary> [Test] public void CanSubtractVectorFromItself() { var copy = CreateVector(Data); var vector = copy.Subtract(copy); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Complex.Zero, vector[i]); } } /// <summary> /// Can subtract a vector from itself using a result vector. /// </summary> [Test] public void CanSubtractVectorFromItselfIntoResultVector() { var vector = CreateVector(Data); var result = CreateVector(Data.Length); vector.Subtract(vector, result); CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Complex.Zero, result[i]); } } /// <summary> /// Can subtract two vectors using itself as result vector. /// </summary> [Test] public void CanSubtractTwoVectorsUsingItselfAsResultVector() { var vector = CreateVector(Data); var other = CreateVector(Data); vector.Subtract(other, vector); CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Complex.Zero, vector[i]); } } /// <summary> /// Can divide a vector by a scalar. /// </summary> [Test] public void CanDivideVectorByScalar() { var copy = CreateVector(Data); var vector = copy.Divide(2.0); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] / 2.0, vector[i]); } vector.Divide(1.0); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] / 2.0, vector[i]); } } /// <summary> /// Can divide a vector by a scalar using a result vector. /// </summary> [Test] public void CanDivideVectorByScalarIntoResultVector() { var vector = CreateVector(Data); var result = CreateVector(Data.Length); vector.Divide(2.0, result); CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] / 2.0, result[i]); } vector.Divide(1.0, result); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i], result[i]); } } /// <summary> /// Can multiply a vector by a scalar. /// </summary> [Test] public void CanMultiplyVectorByScalar() { var copy = CreateVector(Data); var vector = copy.Multiply(2.0); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] * 2.0, vector[i]); } vector.Multiply(1.0); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] * 2.0, vector[i]); } } /// <summary> /// Can multiply a vector by a scalar using a result vector. /// </summary> [Test] public void CanMultiplyVectorByScalarIntoResultVector() { var vector = CreateVector(Data); var result = CreateVector(Data.Length); vector.Multiply(2.0, result); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i], vector[i], "Making sure the original vector wasn't modified."); Assert.AreEqual(Data[i] * 2.0, result[i]); } vector.Multiply(1.0, result); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i], result[i]); } } /// <summary> /// Multiplying by scalar with wrong result vector size throws <c>ArgumentException</c>. /// </summary> [Test] public void MultiplyingScalarWithWrongSizeResultVectorThrowsArgumentException() { var vector = CreateVector(Data.Length); var result = CreateVector(Data.Length + 1); Assert.That(() => vector.Multiply(0.0, result), Throws.ArgumentException); } /// <summary> /// Dividing by scalar with wrong result vector size throws <c>ArgumentException</c>. /// </summary> [Test] public void DividingScalarWithWrongSizeResultVectorThrowsArgumentException() { var vector = CreateVector(Data.Length); var result = CreateVector(Data.Length + 1); Assert.That(() => vector.Divide(0.0, result), Throws.ArgumentException); } /// <summary> /// Can multiply a vector by scalar using operators. /// </summary> [Test] public void CanMultiplyVectorByScalarUsingOperators() { var vector = CreateVector(Data); vector = vector * 2.0; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] * 2.0, vector[i]); } vector = vector * 1.0; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] * 2.0, vector[i]); } vector = CreateVector(Data); vector = 2.0 * vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] * 2.0, vector[i]); } vector = 1.0 * vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] * 2.0, vector[i]); } } /// <summary> /// Can divide a vector by scalar using operators. /// </summary> [Test] public void CanDivideVectorByScalarUsingOperators() { var vector = CreateVector(Data); vector = vector / 2.0; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] / 2.0, vector[i]); } vector = vector / 1.0; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i] / 2.0, vector[i]); } } /// <summary> /// Can calculate the dot product /// </summary> [Test] public void CanDotProduct() { var dataA = CreateVector(Data); var dataB = CreateVector(Data); Assert.AreEqual(new Complex(50, 30), dataA.DotProduct(dataB)); } /// <summary> /// Dot product throws <c>ArgumentException</c> when an argument has different size /// </summary> [Test] public void DotProductWhenDifferentSizeThrowsArgumentException() { var dataA = CreateVector(Data); var dataB = CreateVector(new[] { new Complex(1, 1), new Complex(2, 1), new Complex(3, 1), new Complex(4, 1), new Complex(5, 1), new Complex(6, 1) }); Assert.That(() => dataA.DotProduct(dataB), Throws.ArgumentException); } /// <summary> /// Can calculate the dot product using "*" operator. /// </summary> [Test] public void CanDotProductUsingOperator() { var dataA = CreateVector(Data); var dataB = CreateVector(Data); Assert.AreEqual(new Complex(50, 30), dataA * dataB); } /// <summary> /// Operator "*" throws <c>ArgumentException</c> when the argument has different size. /// </summary> [Test] public void OperatorDotProductWhenDifferentSizeThrowsArgumentException() { var dataA = CreateVector(Data); var dataB = CreateVector(new Complex[] { 1, 2, 3, 4, 5, 6 }); Assert.Throws<ArgumentException>(() => { var d = dataA * dataB; }); } /// <summary> /// Can pointwise multiply two vectors. /// </summary> [Test] public void CanPointwiseMultiply() { var vector1 = CreateVector(Data); var vector2 = vector1.Clone(); var result = vector1.PointwiseMultiply(vector2); for (var i = 0; i < vector1.Count; i++) { Assert.AreEqual(Data[i] * Data[i], result[i]); } } /// <summary> /// Can pointwise multiply two vectors using a result vector. /// </summary> [Test] public void CanPointwiseMultiplyIntoResultVector() { var vector1 = CreateVector(Data); var vector2 = vector1.Clone(); var result = CreateVector(vector1.Count); vector1.PointwiseMultiply(vector2, result); for (var i = 0; i < vector1.Count; i++) { Assert.AreEqual(Data[i] * Data[i], result[i]); } } /// <summary> /// Pointwise multiply with a result vector wrong size throws <c>ArgumentException</c>. /// </summary> [Test] public void PointwiseMultiplyWithInvalidResultLengthThrowsArgumentException() { var vector1 = CreateVector(Data); var vector2 = vector1.Clone(); var result = CreateVector(vector1.Count + 1); Assert.That(() => vector1.PointwiseMultiply(vector2, result), Throws.ArgumentException); } /// <summary> /// Can pointwise divide two vectors using a result vector. /// </summary> [Test] public void CanPointWiseDivide() { var vector1 = CreateVector(Data); var vector2 = vector1.Clone(); var result = vector1.PointwiseDivide(vector2); for (var i = 0; i < vector1.Count; i++) { Assert.AreEqual(Data[i] / Data[i], result[i]); } } /// <summary> /// Can pointwise divide two vectors using a result vector. /// </summary> [Test] public void CanPointWiseDivideIntoResultVector() { var vector1 = CreateVector(Data); var vector2 = vector1.Clone(); var result = CreateVector(vector1.Count); vector1.PointwiseDivide(vector2, result); for (var i = 0; i < vector1.Count; i++) { Assert.AreEqual(Data[i] / Data[i], result[i]); } } /// <summary> /// Pointwise divide with a result vector wrong size throws <c>ArgumentException</c>. /// </summary> [Test] public void PointwiseDivideWithInvalidResultLengthThrowsArgumentException() { var vector1 = CreateVector(Data); var vector2 = vector1.Clone(); var result = CreateVector(vector1.Count + 1); Assert.That(() => vector1.PointwiseDivide(vector2, result), Throws.ArgumentException); } /// <summary> /// Can calculate the outer product of two vectors. /// </summary> [Test] public void CanCalculateOuterProduct() { var vector1 = CreateVector(Data); var vector2 = CreateVector(Data); var m = Vector<Complex>.OuterProduct(vector1, vector2); for (var i = 0; i < vector1.Count; i++) { for (var j = 0; j < vector2.Count; j++) { Assert.AreEqual(m[i, j], vector1[i] * vector2[j]); } } } /// <summary> /// Can calculate the tensor multiply. /// </summary> [Test] public void CanCalculateTensorMultiply() { var vector1 = CreateVector(Data); var vector2 = CreateVector(Data); var m = vector1.OuterProduct(vector2); for (var i = 0; i < vector1.Count; i++) { for (var j = 0; j < vector2.Count; j++) { Assert.AreEqual(m[i, j], vector1[i] * vector2[j]); } } } } }
using System; using System.Windows.Forms; using System.Collections; using System.Drawing; using PrimerProForms; using PrimerProObjects; using GenLib; namespace PrimerProSearch { /// <summary> /// Tone Search for Text Data /// </summary> public class ToneTDSearch : Search { //Search parameters private string m_Tone; //syllograph to be searched private ArrayList m_SelectedTones; //tones to be searched private bool m_ParaFormat; //How to display the results private string m_Title; //search title; private Settings m_Settings; //Application Settings private PSTable m_PSTable; //Parts of Speech private GraphemeInventory m_GI; //Grapheme Inventory private bool m_ViewParaSentWord; //Flag for viewing ParaSentWord number private Font m_DefaultFont; //Default Font //Search definition tags private const string kTone = "tone"; private const string kParaFormat = "paraformat"; //private const string kTitle = "Tone Search"; //private const string kSearch = "Processing Tone Search"; private const string kSeparator = Constants.Tab; public ToneTDSearch(int number, Settings s) : base(number, SearchDefinition.kToneTD) { m_Tone = ""; m_SelectedTones = new ArrayList(); m_ParaFormat = false; m_Settings = s; //m_Title = kTitle; m_Title = m_Settings.LocalizationTable.GetMessage("ToneTDSearchT"); if (m_Title == "") m_Title = "Tone Search"; m_PSTable = m_Settings.PSTable; m_GI = m_Settings.GraphemeInventory; m_ViewParaSentWord = m_Settings.OptionSettings.ViewParaSentWord; m_DefaultFont = m_Settings.OptionSettings.GetDefaultFont(); } public string Tone { get {return m_Tone;} set {m_Tone = value;} } public ArrayList SelectedTones { get { return m_SelectedTones; } set { m_SelectedTones = value; } } public bool ParaFormat { get {return m_ParaFormat;} set {m_ParaFormat = value;} } public string Title { get {return m_Title;} } public PSTable PSTable { get {return m_PSTable;} } public GraphemeInventory GI { get {return m_GI;} } public bool ViewParaSentWord { get { return m_ViewParaSentWord; } } public Font DefaultFont { get { return m_DefaultFont; } } public bool SetupSearch() { bool flag = false; //FormToneTD fpb = new FormToneTD(m_GI, m_DefaultFont); FormToneTD form = new FormToneTD(m_Settings, m_Settings.LocalizationTable); DialogResult dr = form.ShowDialog(); if (dr == DialogResult.OK) { this.SelectedTones = form.SelectedTones; this.ParaFormat = form.ParaFormat; SearchDefinition sd = new SearchDefinition(SearchDefinition.kToneTD); SearchDefinitionParm sdp = null; this.SearchDefinition = sd; String strTone = ""; if (form.SelectedTones.Count > 0) { for (int i = 0; i < form.SelectedTones.Count; i++) { strTone = form.SelectedTones[i].ToString(); sdp = new SearchDefinitionParm(ToneTDSearch.kTone, strTone); sd.AddSearchParm(sdp); } if (form.ParaFormat) { sdp = new SearchDefinitionParm(ToneTDSearch.kParaFormat); sd.AddSearchParm(sdp); } this.SearchDefinition = sd; flag = true; } //else MessageBox.Show("No tone was selected"); else { string strMsg = m_Settings.LocalizationTable.GetMessage("ToneTDSearch2"); if (strMsg == "") strMsg = "No tone was selected"; MessageBox.Show(strMsg); } } return flag; } public bool SetupSearch(SearchDefinition sd) { bool flag = false; string strTag = ""; string strContent = ""; for (int i = 0; i < sd.SearchParmsCount(); i++) { strTag = sd.GetSearchParmAt(i).GetTag(); strContent = sd.GetSearchParmAt(i).GetContent(); if (strTag == ToneTDSearch.kTone) { this.SelectedTones.Add(strContent); flag = true; } if (strTag == ToneTDSearch.kParaFormat) { this.ParaFormat = true; } } this.SearchDefinition = sd; return flag; } public string BuildResults() { string strText = ""; string str = ""; string strSN = Search.TagSN + this.SearchNumber.ToString().Trim(); strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine; strText += this.Title + Environment.NewLine + Environment.NewLine; strText += this.SearchResults; strText += Environment.NewLine; //strText += this.SearchCount.ToString() + " entries found" + Environment.NewLine; str = m_Settings.LocalizationTable.GetMessage("Search2"); if (str == "") str = "entries found"; strText += this.SearchCount.ToString() + Constants.Space + str + Environment.NewLine; strText += Search.TagOpener + Search.TagForwardSlash + strSN + Search.TagCloser; return strText; } public ToneTDSearch ExecuteToneSearch(TextData td) { if (this.ParaFormat) ExecuteToneSearchP(td); else ExecuteToneSearchL(td); return this; } private ToneTDSearch ExecuteToneSearchP(TextData td) { Paragraph para = null; Sentence sent = null; Word wrd = null; string strRslt = ""; string str = ""; int nCount = 0; int nPara = td.ParagraphCount(); str = m_Settings.LocalizationTable.GetMessage("ToneTDSearch1"); if (str == "") str = "Processing Tone Search"; FormProgressBar form = new FormProgressBar(str); form.PB_Init(0, nPara); for (int i = 0; i < nPara; i++) { form.PB_Update(i); para = td.GetParagraph(i); for (int j = 0; j < para.SentenceCount(); j++) { sent = para.GetSentence(j); for (int k = 0; k < sent.WordCount(); k++) { wrd = sent.GetWord(k); if (wrd != null) { bool found = false; int ndx = 0; if (this.SelectedTones.Count > 0) { do { if (wrd.DisplayWord.IndexOf(this.SelectedTones[ndx].ToString()) >= 0) found = true; ndx++; } while ((!found) && (ndx < this.SelectedTones.Count)); } if (found) { strRslt += Constants.kHCOn + wrd.DisplayWord + Constants.kHCOff + Constants.Space; nCount++; } else strRslt += wrd.DisplayWord + Constants.Space; } } strRslt = strRslt.Substring(0, strRslt.Length - 1); //get ride of last space strRslt += sent.EndingPunctuation; strRslt += Constants.Space; } strRslt += Environment.NewLine + Environment.NewLine; } this.SearchResults = strRslt; this.SearchCount = nCount; form.Close(); return this; } private ToneTDSearch ExecuteToneSearchL(TextData td) { Paragraph para = null; Sentence sent = null; Word wrd = null; int nCount = 0; int nPara = td.ParagraphCount(); string strRslt = ""; string str = ""; int nTmp = 0; str = m_Settings.LocalizationTable.GetMessage("ToneTDSearch1"); if (str == "") str = "Processing Tone Search"; FormProgressBar form = new FormProgressBar(str); form.PB_Init(0, nPara); for (int i = 0; i < nPara; i++) { form.PB_Update(i); para = td.GetParagraph(i); for (int j = 0; j < para.SentenceCount(); j++) { sent = para.GetSentence(j); for (int k = 0; k < sent.WordCount(); k++) { wrd = sent.GetWord(k); if (wrd != null) { bool found = false; int ndx = 0; if (this.SelectedTones.Count > 0) { do { if (wrd.DisplayWord.IndexOf(this.SelectedTones[ndx].ToString()) >= 0) found = true; ndx++; } while ((!found) && (ndx < this.SelectedTones.Count)); } if (found) { if (this.ViewParaSentWord) { nTmp = i + 1; strRslt += TextData.kPara + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += ToneTDSearch.kSeparator; nTmp = j + 1; strRslt += TextData.kSent + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += ToneTDSearch.kSeparator; nTmp = k + 1; strRslt += TextData.kWord + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += ToneTDSearch.kSeparator; } strRslt += wrd.DisplayWord; strRslt += Environment.NewLine; nCount++; } } } } } this.SearchResults = strRslt; this.SearchCount = nCount; form.Close(); return this; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using OpenLiveWriter.Controls; namespace OpenLiveWriter.ApplicationFramework { /// <summary> /// WorkspaceColumnPaneLightweightControl. /// </summary> public class WorkspaceColumnPaneLightweightControl : LightweightControl { #region Private Member Variables & Declarations /// <summary> /// Required designer variable. /// </summary> protected Container components = null; /// <summary> /// The control. /// </summary> private Control control; /// <summary> /// The lightweight control. /// </summary> private LightweightControl lightweightControl; /// <summary> /// A value indicating whether a border will be drawn. /// </summary> private bool border; /// <summary> /// A value which indicates whether the pane should be layed out with a fixed height, when /// possible. /// </summary> private bool fixedHeightLayout; /// <summary> /// The fixed height to be used when the FixedHeightLayout property is true. /// </summary> private int fixedHeight; #endregion Private Member Variables & Declarations #region Class Initialization & Termination /// <summary> /// Initializes a new instance of the DummyPaneLightweightControl class. /// </summary> /// <param name="container"></param> public WorkspaceColumnPaneLightweightControl(IContainer container) { /// <summary> /// Required for Windows.Forms Class Composition Designer support /// </summary> container.Add(this); InitializeComponent(); } /// <summary> /// Initializes a new instance of the DummyPaneLightweightControl class. /// </summary> public WorkspaceColumnPaneLightweightControl() { /// <summary> /// Required for Windows.Forms Class Composition Designer support /// </summary> InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion Class Initialization & Termination #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() { ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion #region Public Properties /// <summary> /// Gets or sets the control. /// </summary> public Control Control { get { return control; } set { // If the control is changing, change it. if (control != value) { // Clear. Clear(); // Set the new control. if ((control = value) != null) { control.Parent = Parent; Visible = true; PerformLayout(); Invalidate(); } } } } /// <summary> /// Gets or sets the control. /// </summary> public LightweightControl LightweightControl { get { return lightweightControl; } set { // If the control is changing, change it. if (lightweightControl != value) { // Clear. Clear(); // Set the new control. if ((lightweightControl = value) != null) { lightweightControl.LightweightControlContainerControl = this; Visible = true; PerformLayout(); Invalidate(); } } } } /// <summary> /// Gets or sets a value indicating whether a border will be drawn. /// </summary> public bool Border { get { return border; } set { border = value; } } /// <summary> /// Gets or sets a value which indicates whether the pane should be layed out with a fixed /// height, when possible. /// </summary> public bool FixedHeightLayout { get { return fixedHeightLayout; } set { if (fixedHeightLayout != value) { fixedHeightLayout = value; Parent.PerformLayout(); } } } /// <summary> /// Gets or sets the fixed height to be used when the FixedHeightLayout property is true. /// </summary> public int FixedHeight { get { return fixedHeight; } set { if (fixedHeight != value) { fixedHeight = value; Parent.PerformLayout(); } } } #endregion Public Properties #region Protected Event Overrides /// <summary> /// Raises the Layout event. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected override void OnLayout(EventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnLayout(e); if (Parent == null) return; // Layout the control. if (control != null) { Rectangle layoutRectangle = VirtualClientRectangle; if (border) layoutRectangle.Inflate(-1, -1); control.Bounds = VirtualClientRectangleToParent(layoutRectangle); } else if (lightweightControl != null) { Rectangle layoutRectangle = VirtualClientRectangle; if (border) layoutRectangle.Inflate(-1, -1); lightweightControl.VirtualBounds = layoutRectangle; } } /// <summary> /// Raises the Paint event. /// </summary> /// <param name="e">A PaintEventArgs that contains the event data.</param> protected override void OnPaint(PaintEventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnPaint(e); // If we're drawing a border, draw it. if (border) using (Pen pen = new Pen(ApplicationManager.ApplicationStyle.BorderColor)) e.Graphics.DrawRectangle( pen, VirtualClientRectangle.X, VirtualClientRectangle.Y, VirtualClientRectangle.Width-1, VirtualClientRectangle.Height-1); } /// <summary> /// Raises the VisibleChanged event. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected override void OnVisibleChanged(EventArgs e) { // Call the base class's method so that registered delegates receive the event. base.OnVisibleChanged (e); // Ensure that the Control/LightweightControl Visible property is matched. if (control != null) control.Visible = Visible; else if (lightweightControl != null) lightweightControl.Visible = Visible; } #endregion Protected Event Overrides #region Private Methods /// <summary> /// Clears the workspace column pane. /// </summary> private void Clear() { // If there's a control or a lightweight control, remove it. if (control != null) { control.Parent = null; control.Dispose(); control = null; } else if (lightweightControl != null) { lightweightControl.LightweightControlContainerControl = null; lightweightControl.Dispose(); lightweightControl = null; } // Poof! We're invisible. Visible = false; } #endregion Private Methods } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonViewInspector.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // Custom inspector for the PhotonView component. // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- #if UNITY_5 && !UNITY_5_0 && !UNITY_5_1 && !UNITY_5_2 #define UNITY_MIN_5_3 #endif using System; using UnityEditor; using UnityEngine; using Photon.Pun; [CustomEditor(typeof (PhotonView))] public class PhotonViewInspector : Editor { private PhotonView m_Target; public override void OnInspectorGUI() { this.m_Target = (PhotonView)target; bool isProjectPrefab = EditorUtility.IsPersistent(this.m_Target.gameObject); if (this.m_Target.ObservedComponents == null) { this.m_Target.ObservedComponents = new System.Collections.Generic.List<Component>(); } if (this.m_Target.ObservedComponents.Count == 0) { this.m_Target.ObservedComponents.Add(null); } EditorGUILayout.BeginHorizontal(); // Owner if (isProjectPrefab) { EditorGUILayout.LabelField("Owner:", "Set at runtime"); } else if (!this.m_Target.isOwnerActive) { EditorGUILayout.LabelField("Owner", "Scene"); } else { PhotonPlayer owner = this.m_Target.owner; string ownerInfo = (owner != null) ? owner.NickName : "<no PhotonPlayer found>"; if (string.IsNullOrEmpty(ownerInfo)) { ownerInfo = "<no playername set>"; } EditorGUILayout.LabelField("Owner", "[" + this.m_Target.ownerId + "] " + ownerInfo); } // ownership requests EditorGUI.BeginDisabledGroup(Application.isPlaying); OwnershipOption own = (OwnershipOption)EditorGUILayout.EnumPopup(this.m_Target.ownershipTransfer, GUILayout.Width(100)); if (own != this.m_Target.ownershipTransfer) { // jf: fixed 5 and up prefab not accepting changes if you quit Unity straight after change. // not touching the define nor the rest of the code to avoid bringing more problem than solving. EditorUtility.SetDirty(this.m_Target); Undo.RecordObject(this.m_Target, "Change PhotonView Ownership Transfer"); this.m_Target.ownershipTransfer = own; } EditorGUI.EndDisabledGroup(); EditorGUILayout.EndHorizontal(); // View ID if (isProjectPrefab) { EditorGUILayout.LabelField("View ID", "Set at runtime"); } else if (EditorApplication.isPlaying) { EditorGUILayout.LabelField("View ID", this.m_Target.viewID.ToString()); } else { int idValue = EditorGUILayout.IntField("View ID [1.." + (PhotonNetwork.MAX_VIEW_IDS - 1) + "]", this.m_Target.viewID); if (this.m_Target.viewID != idValue) { Undo.RecordObject(this.m_Target, "Change PhotonView viewID"); this.m_Target.viewID = idValue; } } // Locally Controlled if (EditorApplication.isPlaying) { string masterClientHint = PhotonNetwork.isMasterClient ? "(master)" : ""; EditorGUILayout.Toggle("Controlled locally: " + masterClientHint, this.m_Target.isMine); } // ViewSynchronization (reliability) if (this.m_Target.synchronization == ViewSynchronization.Off) { GUI.color = Color.grey; } EditorGUILayout.PropertyField(serializedObject.FindProperty("synchronization"), new GUIContent("Observe option:")); if (this.m_Target.synchronization != ViewSynchronization.Off && this.m_Target.ObservedComponents.FindAll(item => item != null).Count == 0) { GUILayout.BeginVertical(GUI.skin.box); GUILayout.Label("Warning", EditorStyles.boldLabel); GUILayout.Label("Setting the synchronization option only makes sense if you observe something."); GUILayout.EndVertical(); } DrawSpecificTypeSerializationOptions(); GUI.color = Color.white; DrawObservedComponentsList(); // Cleanup: save and fix look if (GUI.changed) { #if !UNITY_MIN_5_3 EditorUtility.SetDirty(this.m_Target); #endif PhotonViewHandler.HierarchyChange(); // TODO: check if needed } GUI.color = Color.white; #if !UNITY_MIN_5_3 EditorGUIUtility.LookLikeControls(); #endif } private void DrawSpecificTypeSerializationOptions() { if (this.m_Target.ObservedComponents.FindAll(item => item != null && item.GetType() == typeof (Transform)).Count > 0) { this.m_Target.onSerializeTransformOption = (OnSerializeTransform)EditorGUILayout.EnumPopup("Transform Serialization:", this.m_Target.onSerializeTransformOption); } else if (this.m_Target.ObservedComponents.FindAll(item => item != null && item.GetType() == typeof (Rigidbody)).Count > 0 || this.m_Target.ObservedComponents.FindAll(item => item != null && item.GetType() == typeof (Rigidbody2D)).Count > 0) { this.m_Target.onSerializeRigidBodyOption = (OnSerializeRigidBody)EditorGUILayout.EnumPopup("Rigidbody Serialization:", this.m_Target.onSerializeRigidBodyOption); } } private int GetObservedComponentsCount() { int count = 0; for (int i = 0; i < this.m_Target.ObservedComponents.Count; ++i) { if (this.m_Target.ObservedComponents[i] != null) { count++; } } return count; } private void DrawObservedComponentsList() { GUILayout.Space(5); SerializedProperty listProperty = serializedObject.FindProperty("ObservedComponents"); if (listProperty == null) { return; } float containerElementHeight = 22; float containerHeight = listProperty.arraySize*containerElementHeight; bool isOpen = PhotonGUI.ContainerHeaderFoldout("Observed Components (" + GetObservedComponentsCount() + ")", serializedObject.FindProperty("ObservedComponentsFoldoutOpen").boolValue); serializedObject.FindProperty("ObservedComponentsFoldoutOpen").boolValue = isOpen; if (isOpen == false) { containerHeight = 0; } //Texture2D statsIcon = AssetDatabase.LoadAssetAtPath( "Assets/Photon Unity Networking/Editor/PhotonNetwork/PhotonViewStats.png", typeof( Texture2D ) ) as Texture2D; Rect containerRect = PhotonGUI.ContainerBody(containerHeight); bool wasObservedComponentsEmpty = this.m_Target.ObservedComponents.FindAll(item => item != null).Count == 0; if (isOpen == true) { for (int i = 0; i < listProperty.arraySize; ++i) { Rect elementRect = new Rect(containerRect.xMin, containerRect.yMin + containerElementHeight*i, containerRect.width, containerElementHeight); { Rect texturePosition = new Rect(elementRect.xMin + 6, elementRect.yMin + elementRect.height/2f - 1, 9, 5); ReorderableListResources.DrawTexture(texturePosition, ReorderableListResources.texGrabHandle); Rect propertyPosition = new Rect(elementRect.xMin + 20, elementRect.yMin + 3, elementRect.width - 45, 16); EditorGUI.PropertyField(propertyPosition, listProperty.GetArrayElementAtIndex(i), new GUIContent()); //Debug.Log( listProperty.GetArrayElementAtIndex( i ).objectReferenceValue.GetType() ); //Rect statsPosition = new Rect( propertyPosition.xMax + 7, propertyPosition.yMin, statsIcon.width, statsIcon.height ); //ReorderableListResources.DrawTexture( statsPosition, statsIcon ); Rect removeButtonRect = new Rect(elementRect.xMax - PhotonGUI.DefaultRemoveButtonStyle.fixedWidth, elementRect.yMin + 2, PhotonGUI.DefaultRemoveButtonStyle.fixedWidth, PhotonGUI.DefaultRemoveButtonStyle.fixedHeight); GUI.enabled = listProperty.arraySize > 1; if (GUI.Button(removeButtonRect, new GUIContent(ReorderableListResources.texRemoveButton), PhotonGUI.DefaultRemoveButtonStyle)) { listProperty.DeleteArrayElementAtIndex(i); } GUI.enabled = true; if (i < listProperty.arraySize - 1) { texturePosition = new Rect(elementRect.xMin + 2, elementRect.yMax, elementRect.width - 4, 1); PhotonGUI.DrawSplitter(texturePosition); } } } } if (PhotonGUI.AddButton()) { listProperty.InsertArrayElementAtIndex(Mathf.Max(0, listProperty.arraySize - 1)); } serializedObject.ApplyModifiedProperties(); bool isObservedComponentsEmpty = this.m_Target.ObservedComponents.FindAll(item => item != null).Count == 0; if (wasObservedComponentsEmpty == true && isObservedComponentsEmpty == false && this.m_Target.synchronization == ViewSynchronization.Off) { Undo.RecordObject(this.m_Target, "Change PhotonView"); this.m_Target.synchronization = ViewSynchronization.UnreliableOnChange; #if !UNITY_MIN_5_3 EditorUtility.SetDirty(this.m_Target); #endif serializedObject.Update(); } if (wasObservedComponentsEmpty == false && isObservedComponentsEmpty == true) { Undo.RecordObject(this.m_Target, "Change PhotonView"); this.m_Target.synchronization = ViewSynchronization.Off; #if !UNITY_MIN_5_3 EditorUtility.SetDirty(this.m_Target); #endif serializedObject.Update(); } } private static GameObject GetPrefabParent(GameObject mp) { #if UNITY_2_6_1 || UNITY_2_6 || UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 // Unity 3.4 and older use EditorUtility return (EditorUtility.GetPrefabParent(mp) as GameObject); #else // Unity 3.5 uses PrefabUtility return PrefabUtility.GetCorrespondingObjectFromSource(mp) as GameObject; #endif } }
#region /* Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu. All rights reserved. http://code.google.com/p/msnp-sharp/ 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 names of Bas Geertsema or Xih Solutions nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Globalization; namespace MSNPSharp.Core { public class MimeDictionary : SortedList<string, MimeValue> { public new MimeValue this[string name] { get { if (!ContainsKey(name)) return new MimeValue(); return (MimeValue)base[name]; } set { base[name] = value; } } public MimeDictionary() { } public MimeDictionary(byte[] data) { Parse(data); } public int Parse(byte[] data) { int end = MSNHttpUtility.IndexOf(data, "\r\n\r\n"); int ret = end; if (end < 0) ret = end = data.Length; else ret += 4; byte[] mimeData = new byte[end]; Buffer.BlockCopy(data, 0, mimeData, 0, end); string mimeStr = Encoding.UTF8.GetString(mimeData); string[] lines = mimeStr.Trim().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); int i = 0; while (i < lines.Length) { string line = lines[i]; while ((++i < lines.Length) && lines[i].StartsWith("\t")) line += lines[i]; int nameEnd = line.IndexOf(":"); if (nameEnd < 0) continue; string name = line.Substring(0, nameEnd).Trim(); MimeValue val = line.Substring(nameEnd + 1).Trim(); this[name] = val; } return ret; } public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (KeyValuePair<string, MimeValue> pair in this) { sb.Append(pair.Key).Append(": ").Append(pair.Value.ToString()).Append("\r\n"); } return sb.ToString(); } } public class MimeValue { string _val; SortedList<object, string> _attributes = new SortedList<object, string>(); public string Value { get { return _val; } } MimeValue(string main, SortedList<object, string> attributes) { if (attributes == null) throw new ArgumentNullException("attributes"); _val = main; _attributes = attributes; } public MimeValue(string main) { _val = main; } public MimeValue() { _val = string.Empty; } public string this[object attKey] { get { if (!_attributes.ContainsKey(attKey)) return string.Empty; return _attributes[attKey].ToString(); } set { _attributes[attKey] = value; } } public static implicit operator string(MimeValue val) { return val.ToString(); } public static implicit operator MimeValue(string str) { if (str == null) str = string.Empty; str = str.Trim(); string main = str; SortedList<object, string> attributes = new SortedList<object, string>(); if (main.Contains(";")) { main = main.Substring(0, main.IndexOf(";")).Trim(); str = str.Substring(str.IndexOf(";") + 1); string[] parameters = str.Split(';'); int i = 0; foreach (string param in parameters) { int index = param.IndexOf('='); object key = i++; string val = param; //string.Empty; if (index > 0) { key = param.Substring(0, index).Trim(); val = param.Substring(index + 1).Trim(); } else { } attributes[key] = val; } } return new MimeValue(main, attributes); } public void ClearAttributes() { _attributes.Clear(); } public bool HasAttribute(string name) { return _attributes.ContainsKey(name); } public override string ToString() { string str = _val; foreach (KeyValuePair<object, string> att in _attributes) { if (!string.IsNullOrEmpty(str)) str += ";"; str += (att.Key is int) ? att.Value : String.Format(CultureInfo.InvariantCulture, "{0}={1}", att.Key, att.Value); } return str.Trim(); } } };
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Kuchen { public static class GameObjectExtension { public static Subscriber GetSubscriber(this MonoBehaviour behaviour) { return GetOrAddComponent<KuchenSubscriberGameObject>(behaviour.gameObject).Subscriber; } public static SubscribeEventChain Subscribe(this MonoBehaviour behaviour, string topic, Action callback) { return GetSubscriber(behaviour).Subscribe(topic, callback); } public static SubscribeEventChain SubscribeWithTopic(this MonoBehaviour behaviour, string topic, Action<string> callback) { return GetSubscriber(behaviour).SubscribeWithTopic(topic, callback); } public static SubscribeEventChain Subscribe<T1>(this MonoBehaviour behaviour, string topic, Action<T1> callback) { return GetSubscriber(behaviour).Subscribe(topic, callback); } public static SubscribeEventChain SubscribeWithTopic<T1>(this MonoBehaviour behaviour, string topic, Action<string, T1> callback) { return GetSubscriber(behaviour).SubscribeWithTopic(topic, callback); } public static SubscribeEventChain Subscribe<T1, T2>(this MonoBehaviour behaviour, string topic, Action<T1, T2> callback) { return GetSubscriber(behaviour).Subscribe(topic, callback); } public static SubscribeEventChain SubscribeWithTopic<T1, T2>(this MonoBehaviour behaviour, string topic, Action<string, T1, T2> callback) { return GetSubscriber(behaviour).SubscribeWithTopic(topic, callback); } public static SubscribeEventChain Subscribe<T1, T2, T3>(this MonoBehaviour behaviour, string topic, Action<T1, T2, T3> callback) { return GetSubscriber(behaviour).Subscribe(topic, callback); } public static SubscribeEventChain SubscribeWithTopic<T1, T2, T3>(this MonoBehaviour behaviour, string topic, Action<string, T1, T2, T3> callback) { return GetSubscriber(behaviour).SubscribeWithTopic(topic, callback); } public static SubscribeEventChain Subscribe(this MonoBehaviour behaviour, string[] topics, Action callback) { return GetSubscriber(behaviour).Subscribe(topics, callback); } public static SubscribeEventChain SubscribeWithTopic(this MonoBehaviour behaviour, string[] topics, Action<string> callback) { return GetSubscriber(behaviour).SubscribeWithTopic(topics, callback); } public static SubscribeEventChain Subscribe<T1>(this MonoBehaviour behaviour, string[] topics, Action<T1> callback) { return GetSubscriber(behaviour).Subscribe(topics, callback); } public static SubscribeEventChain SubscribeWithTopic<T1>(this MonoBehaviour behaviour, string[] topics, Action<string, T1> callback) { return GetSubscriber(behaviour).SubscribeWithTopic(topics, callback); } public static SubscribeEventChain Subscribe<T1, T2>(this MonoBehaviour behaviour, string[] topics, Action<T1, T2> callback) { return GetSubscriber(behaviour).Subscribe(topics, callback); } public static SubscribeEventChain SubscribeWithTopic<T1, T2>(this MonoBehaviour behaviour, string[] topics, Action<string, T1, T2> callback) { return GetSubscriber(behaviour).SubscribeWithTopic(topics, callback); } public static SubscribeEventChain Subscribe<T1, T2, T3>(this MonoBehaviour behaviour, string[] topics, Action<T1, T2, T3> callback) { return GetSubscriber(behaviour).Subscribe(topics, callback); } public static SubscribeEventChain SubscribeWithTopic<T1, T2, T3>(this MonoBehaviour behaviour, string[] topics, Action<string, T1, T2, T3> callback) { return GetSubscriber(behaviour).SubscribeWithTopic(topics, callback); } public static SubscribeEventChain SubscribeAndStartCoroutine(this MonoBehaviour behaviour, string topic, Func<IEnumerator> callback) { return GetSubscriber(behaviour).Subscribe(topic, () => { behaviour.StartCoroutine(callback()); }); } public static SubscribeEventChain SubscribeWithTopicAndStartCoroutine(this MonoBehaviour behaviour, string topic, Func<string, IEnumerator> callback) { return GetSubscriber(behaviour).SubscribeWithTopic(topic, (t) => { behaviour.StartCoroutine(callback(t)); }); } public static SubscribeEventChain SubscribeAndStartCoroutine<T1>(this MonoBehaviour behaviour, string topic, Func<T1, IEnumerator> callback) { return GetSubscriber(behaviour).Subscribe<T1>(topic, (a1) => { behaviour.StartCoroutine(callback(a1)); }); } public static SubscribeEventChain SubscribeWithTopicAndStartCoroutine<T1>(this MonoBehaviour behaviour, string topic, Func<string, T1, IEnumerator> callback) { return GetSubscriber(behaviour).SubscribeWithTopic<T1>(topic, (t, a1) => { behaviour.StartCoroutine(callback(t, a1)); }); } public static SubscribeEventChain SubscribeAndStartCoroutine<T1, T2>(this MonoBehaviour behaviour, string topic, Func<T1, T2, IEnumerator> callback) { return GetSubscriber(behaviour).Subscribe<T1, T2>(topic, (a1, a2) => { behaviour.StartCoroutine(callback(a1, a2)); }); } public static SubscribeEventChain SubscribeWithTopicAndStartCoroutine<T1, T2>(this MonoBehaviour behaviour, string topic, Func<string, T1, T2, IEnumerator> callback) { return GetSubscriber(behaviour).SubscribeWithTopic<T1, T2>(topic, (t, a1, a2) => { behaviour.StartCoroutine(callback(t, a1, a2)); }); } public static SubscribeEventChain SubscribeAndStartCoroutine<T1, T2, T3>(this MonoBehaviour behaviour, string topic, Func<T1, T2, T3, IEnumerator> callback) { return GetSubscriber(behaviour).Subscribe<T1, T2, T3>(topic, (a1, a2, a3) => { behaviour.StartCoroutine(callback(a1, a2, a3)); }); } public static SubscribeEventChain SubscribeWithTopicAndStartCoroutine<T1, T2, T3>(this MonoBehaviour behaviour, string topic, Func<string, T1, T2, T3, IEnumerator> callback) { return GetSubscriber(behaviour).SubscribeWithTopic<T1, T2, T3>(topic, (t, a1, a2, a3) => { behaviour.StartCoroutine(callback(t, a1, a2, a3)); }); } public static void Unsubscribe(this MonoBehaviour behaviour) { GetSubscriber(behaviour).Unsubscribe(); } public static void Unsubscribe(this MonoBehaviour behaviour, string topic) { GetSubscriber(behaviour).Unsubscribe(topic); } public static void Unsubscribe(this MonoBehaviour behaviour, ISubscribeEvent se) { GetSubscriber(behaviour).Unsubscribe(se); } public static void Unsubscribe(this MonoBehaviour behaviour, SubscribeEventChain sec) { GetSubscriber(behaviour).Unsubscribe(sec); } public static void Publish(this MonoBehaviour behaviour, string topic) { Publisher.Publish(topic); } public static void Publish<T1>(this MonoBehaviour behaviour, string topic, T1 arg1) { Publisher.Publish(topic, arg1); } public static void Publish<T1, T2>(this MonoBehaviour behaviour, string topic, T1 arg1, T2 arg2) { Publisher.Publish(topic, arg1, arg2); } public static void Publish<T1, T2, T3>(this MonoBehaviour behaviour, string topic, T1 arg1, T2 arg2, T3 arg3) { Publisher.Publish(topic, arg1, arg2, arg3); } public static void Mute(this MonoBehaviour behaviour, string topic) { GetSubscriber(behaviour).Mute(topic); } public static void Unmute(this MonoBehaviour behaviour, string topic) { GetSubscriber(behaviour).Unmute(topic); } public static Coroutine WaitForMessage(this MonoBehaviour behaviour, string topic, float timeout = 0.0f) { return behaviour.WaitForMessage(new string[]{topic}, timeout); } public static Coroutine WaitForMessage(this MonoBehaviour behaviour, string[] topics, float timeout = 0.0f) { var subscriberObject = GetOrAddComponent<KuchenSubscriberGameObject>(behaviour.gameObject); return behaviour.StartCoroutine(Util.Coroutine.WaitForMessage(subscriberObject.Subscriber, topics, timeout)); } private static T GetOrAddComponent<T>(GameObject gameObject) where T : Component { var component = gameObject.GetComponent<T>(); if(component == null) component = gameObject.AddComponent<T>(); return component; } } }
// 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; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Xml; using Microsoft.Win32; namespace System.Security.Cryptography.Xml { public class SignedXml { protected Signature m_signature; protected string m_strSigningKeyName; private AsymmetricAlgorithm _signingKey; private XmlDocument _containingDocument = null; private IEnumerator _keyInfoEnum = null; private X509Certificate2Collection _x509Collection = null; private IEnumerator _x509Enum = null; private bool[] _refProcessed = null; private int[] _refLevelCache = null; internal XmlResolver _xmlResolver = null; internal XmlElement _context = null; private bool _bResolverSet = false; private Func<SignedXml, bool> _signatureFormatValidator = DefaultSignatureFormatValidator; private Collection<string> _safeCanonicalizationMethods; // Built in canonicalization algorithm URIs private static IList<string> s_knownCanonicalizationMethods = null; // Built in transform algorithm URIs (excluding canonicalization URIs) private static IList<string> s_defaultSafeTransformMethods = null; // additional HMAC Url identifiers private const string XmlDsigMoreHMACMD5Url = "http://www.w3.org/2001/04/xmldsig-more#hmac-md5"; private const string XmlDsigMoreHMACSHA256Url = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"; private const string XmlDsigMoreHMACSHA384Url = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"; private const string XmlDsigMoreHMACSHA512Url = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"; private const string XmlDsigMoreHMACRIPEMD160Url = "http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160"; // defines the XML encryption processing rules private EncryptedXml _exml = null; // // public constant Url identifiers most frequently used within the XML Signature classes // public const string XmlDsigNamespaceUrl = "http://www.w3.org/2000/09/xmldsig#"; public const string XmlDsigMinimalCanonicalizationUrl = "http://www.w3.org/2000/09/xmldsig#minimal"; public const string XmlDsigCanonicalizationUrl = XmlDsigC14NTransformUrl; public const string XmlDsigCanonicalizationWithCommentsUrl = XmlDsigC14NWithCommentsTransformUrl; public const string XmlDsigSHA1Url = "http://www.w3.org/2000/09/xmldsig#sha1"; public const string XmlDsigDSAUrl = "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; public const string XmlDsigRSASHA1Url = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; public const string XmlDsigHMACSHA1Url = "http://www.w3.org/2000/09/xmldsig#hmac-sha1"; public const string XmlDsigSHA256Url = "http://www.w3.org/2001/04/xmlenc#sha256"; public const string XmlDsigRSASHA256Url = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; // Yes, SHA384 is in the xmldsig-more namespace even though all the other SHA variants are in xmlenc. That's the standard. public const string XmlDsigSHA384Url = "http://www.w3.org/2001/04/xmldsig-more#sha384"; public const string XmlDsigRSASHA384Url = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"; public const string XmlDsigSHA512Url = "http://www.w3.org/2001/04/xmlenc#sha512"; public const string XmlDsigRSASHA512Url = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"; public const string XmlDsigC14NTransformUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; public const string XmlDsigC14NWithCommentsTransformUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; public const string XmlDsigExcC14NTransformUrl = "http://www.w3.org/2001/10/xml-exc-c14n#"; public const string XmlDsigExcC14NWithCommentsTransformUrl = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"; public const string XmlDsigBase64TransformUrl = "http://www.w3.org/2000/09/xmldsig#base64"; public const string XmlDsigXPathTransformUrl = "http://www.w3.org/TR/1999/REC-xpath-19991116"; public const string XmlDsigXsltTransformUrl = "http://www.w3.org/TR/1999/REC-xslt-19991116"; public const string XmlDsigEnvelopedSignatureTransformUrl = "http://www.w3.org/2000/09/xmldsig#enveloped-signature"; public const string XmlDecryptionTransformUrl = "http://www.w3.org/2002/07/decrypt#XML"; public const string XmlLicenseTransformUrl = "urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform"; // // public constructors // public SignedXml() { Initialize(null); } public SignedXml(XmlDocument document) { if (document == null) throw new ArgumentNullException(nameof(document)); Initialize(document.DocumentElement); } public SignedXml(XmlElement elem) { if (elem == null) throw new ArgumentNullException(nameof(elem)); Initialize(elem); } private void Initialize(XmlElement element) { _containingDocument = (element == null ? null : element.OwnerDocument); _context = element; m_signature = new Signature(); m_signature.SignedXml = this; m_signature.SignedInfo = new SignedInfo(); _signingKey = null; _safeCanonicalizationMethods = new Collection<string>(KnownCanonicalizationMethods); } // // public properties // /// <internalonly/> public string SigningKeyName { get { return m_strSigningKeyName; } set { m_strSigningKeyName = value; } } public XmlResolver Resolver { // This property only has a setter. The rationale for this is that we don't have a good value // to return when it has not been explicitely set, as we are using XmlSecureResolver by default set { _xmlResolver = value; _bResolverSet = true; } } internal bool ResolverSet { get { return _bResolverSet; } } public Func<SignedXml, bool> SignatureFormatValidator { get { return _signatureFormatValidator; } set { _signatureFormatValidator = value; } } public Collection<string> SafeCanonicalizationMethods { get { return _safeCanonicalizationMethods; } } public AsymmetricAlgorithm SigningKey { get { return _signingKey; } set { _signingKey = value; } } public EncryptedXml EncryptedXml { get { if (_exml == null) _exml = new EncryptedXml(_containingDocument); // default processing rules return _exml; } set { _exml = value; } } public Signature Signature { get { return m_signature; } } public SignedInfo SignedInfo { get { return m_signature.SignedInfo; } } public string SignatureMethod { get { return m_signature.SignedInfo.SignatureMethod; } } public string SignatureLength { get { return m_signature.SignedInfo.SignatureLength; } } public byte[] SignatureValue { get { return m_signature.SignatureValue; } } public KeyInfo KeyInfo { get { return m_signature.KeyInfo; } set { m_signature.KeyInfo = value; } } public XmlElement GetXml() { // If we have a document context, then return a signature element in this context if (_containingDocument != null) return m_signature.GetXml(_containingDocument); else return m_signature.GetXml(); } public void LoadXml(XmlElement value) { if (value == null) throw new ArgumentNullException(nameof(value)); m_signature.LoadXml(value); if (_context == null) { _context = value; } _bCacheValid = false; } // // public methods // public void AddReference(Reference reference) { m_signature.SignedInfo.AddReference(reference); } public void AddObject(DataObject dataObject) { m_signature.AddObject(dataObject); } public bool CheckSignature() { AsymmetricAlgorithm signingKey; return CheckSignatureReturningKey(out signingKey); } public bool CheckSignatureReturningKey(out AsymmetricAlgorithm signingKey) { SignedXmlDebugLog.LogBeginSignatureVerification(this, _context); signingKey = null; bool bRet = false; AsymmetricAlgorithm key = null; if (!CheckSignatureFormat()) { return false; } do { key = GetPublicKey(); if (key != null) { bRet = CheckSignature(key); SignedXmlDebugLog.LogVerificationResult(this, key, bRet); } } while (key != null && bRet == false); signingKey = key; return bRet; } public bool CheckSignature(AsymmetricAlgorithm key) { if (!CheckSignatureFormat()) { return false; } if (!CheckSignedInfo(key)) { SignedXmlDebugLog.LogVerificationFailure(this, SR.Log_VerificationFailed_SignedInfo); return false; } // Now is the time to go through all the references and see if their DigestValues are good if (!CheckDigestedReferences()) { SignedXmlDebugLog.LogVerificationFailure(this, SR.Log_VerificationFailed_References); return false; } SignedXmlDebugLog.LogVerificationResult(this, key, true); return true; } public bool CheckSignature(KeyedHashAlgorithm macAlg) { if (!CheckSignatureFormat()) { return false; } if (!CheckSignedInfo(macAlg)) { SignedXmlDebugLog.LogVerificationFailure(this, SR.Log_VerificationFailed_SignedInfo); return false; } if (!CheckDigestedReferences()) { SignedXmlDebugLog.LogVerificationFailure(this, SR.Log_VerificationFailed_References); return false; } SignedXmlDebugLog.LogVerificationResult(this, macAlg, true); return true; } public bool CheckSignature(X509Certificate2 certificate, bool verifySignatureOnly) { if (!verifySignatureOnly) { // Check key usages to make sure it is good for signing. foreach (X509Extension extension in certificate.Extensions) { if (string.Compare(extension.Oid.Value, "2.5.29.15" /* szOID_KEY_USAGE */, StringComparison.OrdinalIgnoreCase) == 0) { X509KeyUsageExtension keyUsage = new X509KeyUsageExtension(); keyUsage.CopyFrom(extension); SignedXmlDebugLog.LogVerifyKeyUsage(this, certificate, keyUsage); bool validKeyUsage = (keyUsage.KeyUsages & X509KeyUsageFlags.DigitalSignature) != 0 || (keyUsage.KeyUsages & X509KeyUsageFlags.NonRepudiation) != 0; if (!validKeyUsage) { SignedXmlDebugLog.LogVerificationFailure(this, SR.Log_VerificationFailed_X509KeyUsage); return false; } break; } } // Do the chain verification to make sure the certificate is valid. X509Chain chain = new X509Chain(); chain.ChainPolicy.ExtraStore.AddRange(BuildBagOfCerts()); bool chainVerified = chain.Build(certificate); SignedXmlDebugLog.LogVerifyX509Chain(this, chain, certificate); if (!chainVerified) { SignedXmlDebugLog.LogVerificationFailure(this, SR.Log_VerificationFailed_X509Chain); return false; } } using (AsymmetricAlgorithm publicKey = Utils.GetAnyPublicKey(certificate)) { if (!CheckSignature(publicKey)) { return false; } } SignedXmlDebugLog.LogVerificationResult(this, certificate, true); return true; } public void ComputeSignature() { SignedXmlDebugLog.LogBeginSignatureComputation(this, _context); BuildDigestedReferences(); // Load the key AsymmetricAlgorithm key = SigningKey; if (key == null) throw new CryptographicException(SR.Cryptography_Xml_LoadKeyFailed); // Check the signature algorithm associated with the key so that we can accordingly set the signature method if (SignedInfo.SignatureMethod == null) { if (key is DSA) { SignedInfo.SignatureMethod = XmlDsigDSAUrl; } else if (key is RSA) { // Default to RSA-SHA1 if (SignedInfo.SignatureMethod == null) SignedInfo.SignatureMethod = XmlDsigRSASHA256Url; } else { throw new CryptographicException(SR.Cryptography_Xml_CreatedKeyFailed); } } // See if there is a signature description class defined in the Config file SignatureDescription signatureDescription = CryptoHelpers.CreateFromName(SignedInfo.SignatureMethod) as SignatureDescription; if (signatureDescription == null) throw new CryptographicException(SR.Cryptography_Xml_SignatureDescriptionNotCreated); HashAlgorithm hashAlg = signatureDescription.CreateDigest(); if (hashAlg == null) throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); byte[] hashvalue = GetC14NDigest(hashAlg); AsymmetricSignatureFormatter asymmetricSignatureFormatter = signatureDescription.CreateFormatter(key); SignedXmlDebugLog.LogSigning(this, key, signatureDescription, hashAlg, asymmetricSignatureFormatter); m_signature.SignatureValue = asymmetricSignatureFormatter.CreateSignature(hashAlg); } public void ComputeSignature(KeyedHashAlgorithm macAlg) { if (macAlg == null) throw new ArgumentNullException(nameof(macAlg)); HMAC hash = macAlg as HMAC; if (hash == null) throw new CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch); int signatureLength; if (m_signature.SignedInfo.SignatureLength == null) signatureLength = hash.HashSize; else signatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength, null); // signatureLength should be less than hash size if (signatureLength < 0 || signatureLength > hash.HashSize) throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength); if (signatureLength % 8 != 0) throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength2); BuildDigestedReferences(); switch (hash.HashName) { case "SHA1": SignedInfo.SignatureMethod = SignedXml.XmlDsigHMACSHA1Url; break; case "SHA256": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA256Url; break; case "SHA384": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA384Url; break; case "SHA512": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA512Url; break; case "MD5": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACMD5Url; break; case "RIPEMD160": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACRIPEMD160Url; break; default: throw new CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch); } byte[] hashValue = GetC14NDigest(hash); SignedXmlDebugLog.LogSigning(this, hash); m_signature.SignatureValue = new byte[signatureLength / 8]; Buffer.BlockCopy(hashValue, 0, m_signature.SignatureValue, 0, signatureLength / 8); } // // virtual methods // protected virtual AsymmetricAlgorithm GetPublicKey() { if (KeyInfo == null) throw new CryptographicException(SR.Cryptography_Xml_KeyInfoRequired); if (_x509Enum != null) { AsymmetricAlgorithm key = GetNextCertificatePublicKey(); if (key != null) return key; } if (_keyInfoEnum == null) _keyInfoEnum = KeyInfo.GetEnumerator(); // In our implementation, we move to the next KeyInfo clause which is an RSAKeyValue, DSAKeyValue or KeyInfoX509Data while (_keyInfoEnum.MoveNext()) { RSAKeyValue rsaKeyValue = _keyInfoEnum.Current as RSAKeyValue; if (rsaKeyValue != null) return rsaKeyValue.Key; DSAKeyValue dsaKeyValue = _keyInfoEnum.Current as DSAKeyValue; if (dsaKeyValue != null) return dsaKeyValue.Key; KeyInfoX509Data x509Data = _keyInfoEnum.Current as KeyInfoX509Data; if (x509Data != null) { _x509Collection = Utils.BuildBagOfCerts(x509Data, CertUsageType.Verification); if (_x509Collection.Count > 0) { _x509Enum = _x509Collection.GetEnumerator(); AsymmetricAlgorithm key = GetNextCertificatePublicKey(); if (key != null) return key; } } } return null; } private X509Certificate2Collection BuildBagOfCerts() { X509Certificate2Collection collection = new X509Certificate2Collection(); if (KeyInfo != null) { foreach (KeyInfoClause clause in KeyInfo) { KeyInfoX509Data x509Data = clause as KeyInfoX509Data; if (x509Data != null) collection.AddRange(Utils.BuildBagOfCerts(x509Data, CertUsageType.Verification)); } } return collection; } private AsymmetricAlgorithm GetNextCertificatePublicKey() { while (_x509Enum.MoveNext()) { X509Certificate2 certificate = (X509Certificate2)_x509Enum.Current; if (certificate != null) return Utils.GetAnyPublicKey(certificate); } return null; } public virtual XmlElement GetIdElement(XmlDocument document, string idValue) { return DefaultGetIdElement(document, idValue); } internal static XmlElement DefaultGetIdElement(XmlDocument document, string idValue) { if (document == null) return null; try { XmlConvert.VerifyNCName(idValue); } catch (XmlException) { // Identifiers are required to be an NCName // (xml:id version 1.0, part 4, paragraph 2, bullet 1) // // If it isn't an NCName, it isn't allowed to match. return null; } // Get the element with idValue XmlElement elem = document.GetElementById(idValue); if (elem != null) { // Have to check for duplicate ID values from the DTD. XmlDocument docClone = (XmlDocument)document.CloneNode(true); XmlElement cloneElem = docClone.GetElementById(idValue); // If it's null here we want to know about it, because it means that // GetElementById failed to work across the cloning, and our uniqueness // test is invalid. System.Diagnostics.Debug.Assert(cloneElem != null); // Guard against null anyways if (cloneElem != null) { cloneElem.Attributes.RemoveAll(); XmlElement cloneElem2 = docClone.GetElementById(idValue); if (cloneElem2 != null) { throw new CryptographicException( SR.Cryptography_Xml_InvalidReference); } } return elem; } elem = GetSingleReferenceTarget(document, "Id", idValue); if (elem != null) return elem; elem = GetSingleReferenceTarget(document, "id", idValue); if (elem != null) return elem; elem = GetSingleReferenceTarget(document, "ID", idValue); return elem; } // // private methods // private bool _bCacheValid = false; private byte[] _digestedSignedInfo = null; private static bool DefaultSignatureFormatValidator(SignedXml signedXml) { // Reject the signature if it uses a truncated HMAC if (signedXml.DoesSignatureUseTruncatedHmac()) { return false; } // Reject the signature if it uses a canonicalization algorithm other than // one of the ones explicitly allowed if (!signedXml.DoesSignatureUseSafeCanonicalizationMethod()) { return false; } // Otherwise accept it return true; } // Validation function to see if the current signature is signed with a truncated HMAC - one which // has a signature length of fewer bits than the whole HMAC output. private bool DoesSignatureUseTruncatedHmac() { // If we're not using the SignatureLength property, then we're not truncating the signature length if (SignedInfo.SignatureLength == null) { return false; } // See if we're signed witn an HMAC algorithm HMAC hmac = CryptoHelpers.CreateFromName(SignatureMethod) as HMAC; if (hmac == null) { // We aren't signed with an HMAC algorithm, so we cannot have a truncated HMAC return false; } // Figure out how many bits the signature is using int actualSignatureSize = 0; if (!int.TryParse(SignedInfo.SignatureLength, out actualSignatureSize)) { // If the value wasn't a valid integer, then we'll conservatively reject it all together return true; } // Make sure the full HMAC signature size is the same size that was specified in the XML // signature. If the actual signature size is not exactly the same as the full HMAC size, then // reject the signature. return actualSignatureSize != hmac.HashSize; } // Validation function to see if the signature uses a canonicalization algorithm from our list // of approved algorithm URIs. private bool DoesSignatureUseSafeCanonicalizationMethod() { foreach (string safeAlgorithm in SafeCanonicalizationMethods) { if (string.Equals(safeAlgorithm, SignedInfo.CanonicalizationMethod, StringComparison.OrdinalIgnoreCase)) { return true; } } SignedXmlDebugLog.LogUnsafeCanonicalizationMethod(this, SignedInfo.CanonicalizationMethod, SafeCanonicalizationMethods); return false; } private bool ReferenceUsesSafeTransformMethods(Reference reference) { TransformChain transformChain = reference.TransformChain; int transformCount = transformChain.Count; for (int i = 0; i < transformCount; i++) { Transform transform = transformChain[i]; if (!IsSafeTransform(transform.Algorithm)) { return false; } } return true; } private bool IsSafeTransform(string transformAlgorithm) { // All canonicalization algorithms are valid transform algorithms. foreach (string safeAlgorithm in SafeCanonicalizationMethods) { if (string.Equals(safeAlgorithm, transformAlgorithm, StringComparison.OrdinalIgnoreCase)) { return true; } } foreach (string safeAlgorithm in DefaultSafeTransformMethods) { if (string.Equals(safeAlgorithm, transformAlgorithm, StringComparison.OrdinalIgnoreCase)) { return true; } } SignedXmlDebugLog.LogUnsafeTransformMethod( this, transformAlgorithm, SafeCanonicalizationMethods, DefaultSafeTransformMethods); return false; } // Get a list of the built in canonicalization algorithms, as well as any that the machine admin has // added to the valid set. private static IList<string> KnownCanonicalizationMethods { get { if (s_knownCanonicalizationMethods == null) { // Start with the list that the machine admin added, if any List<string> safeAlgorithms = new List<string>(); // Built in algorithms safeAlgorithms.Add(XmlDsigC14NTransformUrl); safeAlgorithms.Add(XmlDsigC14NWithCommentsTransformUrl); safeAlgorithms.Add(XmlDsigExcC14NTransformUrl); safeAlgorithms.Add(XmlDsigExcC14NWithCommentsTransformUrl); s_knownCanonicalizationMethods = safeAlgorithms; } return s_knownCanonicalizationMethods; } } private static IList<string> DefaultSafeTransformMethods { get { if (s_defaultSafeTransformMethods == null) { List<string> safeAlgorithms = new List<string>(); // Built in algorithms // KnownCanonicalizationMethods don't need to be added here, because // the validator will automatically accept those. // // xmldsig 6.6.1: // Any canonicalization algorithm that can be used for // CanonicalizationMethod can be used as a Transform. safeAlgorithms.Add(XmlDsigEnvelopedSignatureTransformUrl); safeAlgorithms.Add(XmlDsigBase64TransformUrl); safeAlgorithms.Add(XmlLicenseTransformUrl); safeAlgorithms.Add(XmlDecryptionTransformUrl); s_defaultSafeTransformMethods = safeAlgorithms; } return s_defaultSafeTransformMethods; } } private byte[] GetC14NDigest(HashAlgorithm hash) { bool isKeyedHashAlgorithm = hash is KeyedHashAlgorithm; if (isKeyedHashAlgorithm || !_bCacheValid || !SignedInfo.CacheValid) { string baseUri = (_containingDocument == null ? null : _containingDocument.BaseURI); XmlResolver resolver = (_bResolverSet ? _xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); XmlDocument doc = Utils.PreProcessElementInput(SignedInfo.GetXml(), resolver, baseUri); // Add non default namespaces in scope CanonicalXmlNodeList namespaces = (_context == null ? null : Utils.GetPropagatedAttributes(_context)); SignedXmlDebugLog.LogNamespacePropagation(this, namespaces); Utils.AddNamespaces(doc.DocumentElement, namespaces); Transform c14nMethodTransform = SignedInfo.CanonicalizationMethodObject; c14nMethodTransform.Resolver = resolver; c14nMethodTransform.BaseURI = baseUri; SignedXmlDebugLog.LogBeginCanonicalization(this, c14nMethodTransform); c14nMethodTransform.LoadInput(doc); SignedXmlDebugLog.LogCanonicalizedOutput(this, c14nMethodTransform); _digestedSignedInfo = c14nMethodTransform.GetDigestedOutput(hash); _bCacheValid = !isKeyedHashAlgorithm; } return _digestedSignedInfo; } private int GetReferenceLevel(int index, ArrayList references) { if (_refProcessed[index]) return _refLevelCache[index]; _refProcessed[index] = true; Reference reference = (Reference)references[index]; if (reference.Uri == null || reference.Uri.Length == 0 || (reference.Uri.Length > 0 && reference.Uri[0] != '#')) { _refLevelCache[index] = 0; return 0; } if (reference.Uri.Length > 0 && reference.Uri[0] == '#') { string idref = Utils.ExtractIdFromLocalUri(reference.Uri); if (idref == "xpointer(/)") { _refLevelCache[index] = 0; return 0; } // If this is pointing to another reference for (int j = 0; j < references.Count; ++j) { if (((Reference)references[j]).Id == idref) { _refLevelCache[index] = GetReferenceLevel(j, references) + 1; return (_refLevelCache[index]); } } // Then the reference points to an object tag _refLevelCache[index] = 0; return 0; } // Malformed reference throw new CryptographicException(SR.Cryptography_Xml_InvalidReference); } private class ReferenceLevelSortOrder : IComparer { private ArrayList _references = null; public ReferenceLevelSortOrder() { } public ArrayList References { get { return _references; } set { _references = value; } } public int Compare(object a, object b) { Reference referenceA = a as Reference; Reference referenceB = b as Reference; // Get the indexes int iIndexA = 0; int iIndexB = 0; int i = 0; foreach (Reference reference in References) { if (reference == referenceA) iIndexA = i; if (reference == referenceB) iIndexB = i; i++; } int iLevelA = referenceA.SignedXml.GetReferenceLevel(iIndexA, References); int iLevelB = referenceB.SignedXml.GetReferenceLevel(iIndexB, References); return iLevelA.CompareTo(iLevelB); } } private void BuildDigestedReferences() { // Default the DigestMethod and Canonicalization ArrayList references = SignedInfo.References; // Reset the cache _refProcessed = new bool[references.Count]; _refLevelCache = new int[references.Count]; ReferenceLevelSortOrder sortOrder = new ReferenceLevelSortOrder(); sortOrder.References = references; // Don't alter the order of the references array list ArrayList sortedReferences = new ArrayList(); foreach (Reference reference in references) { sortedReferences.Add(reference); } sortedReferences.Sort(sortOrder); CanonicalXmlNodeList nodeList = new CanonicalXmlNodeList(); foreach (DataObject obj in m_signature.ObjectList) { nodeList.Add(obj.GetXml()); } foreach (Reference reference in sortedReferences) { // If no DigestMethod has yet been set, default it to sha1 if (reference.DigestMethod == null) reference.DigestMethod = Reference.DefaultDigestMethod; SignedXmlDebugLog.LogSigningReference(this, reference); reference.UpdateHashValue(_containingDocument, nodeList); // If this reference has an Id attribute, add it if (reference.Id != null) nodeList.Add(reference.GetXml()); } } private bool CheckDigestedReferences() { ArrayList references = m_signature.SignedInfo.References; for (int i = 0; i < references.Count; ++i) { Reference digestedReference = (Reference)references[i]; if (!ReferenceUsesSafeTransformMethods(digestedReference)) { return false; } SignedXmlDebugLog.LogVerifyReference(this, digestedReference); byte[] calculatedHash = null; try { calculatedHash = digestedReference.CalculateHashValue(_containingDocument, m_signature.ReferencedItems); } catch (CryptoSignedXmlRecursionException) { SignedXmlDebugLog.LogSignedXmlRecursionLimit(this, digestedReference); return false; } // Compare both hashes SignedXmlDebugLog.LogVerifyReferenceHash(this, digestedReference, calculatedHash, digestedReference.DigestValue); if (!CryptographicEquals(calculatedHash, digestedReference.DigestValue)) { return false; } } return true; } // Methods _must_ be marked both No Inlining and No Optimization to be fully opted out of optimization. // This is because if a candidate method is inlined, its method level attributes, including the NoOptimization // attribute, are lost. // This method makes no attempt to disguise the length of either of its inputs. It is assumed the attacker has // knowledge of the algorithms used, and thus the output length. Length is difficult to properly blind in modern CPUs. [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private static bool CryptographicEquals(byte[] a, byte[] b) { System.Diagnostics.Debug.Assert(a != null); System.Diagnostics.Debug.Assert(b != null); int result = 0; // Short cut if the lengths are not identical if (a.Length != b.Length) return false; unchecked { // Normally this caching doesn't matter, but with the optimizer off, this nets a non-trivial speedup. int aLength = a.Length; for (int i = 0; i < aLength; i++) // We use subtraction here instead of XOR because the XOR algorithm gets ever so // slightly faster as more and more differences pile up. // This cannot overflow more than once (and back to 0) because bytes are 1 byte // in length, and result is 4 bytes. The OR propagates all set bytes, so the differences // can't add up and overflow a second time. result = result | (a[i] - b[i]); } return (0 == result); } // If we have a signature format validation callback, check to see if this signature's format (not // the signautre itself) is valid according to the validator. A return value of true indicates that // the signature format is acceptable, false means that the format is not valid. private bool CheckSignatureFormat() { if (_signatureFormatValidator == null) { // No format validator means that we default to accepting the signature. (This is // effectively compatibility mode with v3.5). return true; } SignedXmlDebugLog.LogBeginCheckSignatureFormat(this, _signatureFormatValidator); bool formatValid = _signatureFormatValidator(this); SignedXmlDebugLog.LogFormatValidationResult(this, formatValid); return formatValid; } private bool CheckSignedInfo(AsymmetricAlgorithm key) { if (key == null) throw new ArgumentNullException(nameof(key)); SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo); SignatureDescription signatureDescription = CryptoHelpers.CreateFromName(SignatureMethod) as SignatureDescription; if (signatureDescription == null) throw new CryptographicException(SR.Cryptography_Xml_SignatureDescriptionNotCreated); // Let's see if the key corresponds with the SignatureMethod Type ta = Type.GetType(signatureDescription.KeyAlgorithm); if (!IsKeyTheCorrectAlgorithm(key, ta)) return false; HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest(); if (hashAlgorithm == null) throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); byte[] hashval = GetC14NDigest(hashAlgorithm); AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key); SignedXmlDebugLog.LogVerifySignedInfo(this, key, signatureDescription, hashAlgorithm, asymmetricSignatureDeformatter, hashval, m_signature.SignatureValue); return asymmetricSignatureDeformatter.VerifySignature(hashval, m_signature.SignatureValue); } private bool CheckSignedInfo(KeyedHashAlgorithm macAlg) { if (macAlg == null) throw new ArgumentNullException(nameof(macAlg)); SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo); int signatureLength; if (m_signature.SignedInfo.SignatureLength == null) signatureLength = macAlg.HashSize; else signatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength, null); // signatureLength should be less than hash size if (signatureLength < 0 || signatureLength > macAlg.HashSize) throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength); if (signatureLength % 8 != 0) throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength2); if (m_signature.SignatureValue == null) throw new CryptographicException(SR.Cryptography_Xml_SignatureValueRequired); if (m_signature.SignatureValue.Length != signatureLength / 8) throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength); // Calculate the hash byte[] hashValue = GetC14NDigest(macAlg); SignedXmlDebugLog.LogVerifySignedInfo(this, macAlg, hashValue, m_signature.SignatureValue); for (int i = 0; i < m_signature.SignatureValue.Length; i++) { if (m_signature.SignatureValue[i] != hashValue[i]) return false; } return true; } private static XmlElement GetSingleReferenceTarget(XmlDocument document, string idAttributeName, string idValue) { // idValue has already been tested as an NCName (unless overridden for compatibility), so there's no // escaping that needs to be done here. string xPath = "//*[@" + idAttributeName + "=\"" + idValue + "\"]"; // http://www.w3.org/TR/xmldsig-core/#sec-ReferenceProcessingModel says that for the form URI="#chapter1": // // Identifies a node-set containing the element with ID attribute value 'chapter1' ... // // Note that it uses the singular. Therefore, if the match is ambiguous, we should consider the document invalid. // // In this case, we'll treat it the same as having found nothing across all fallbacks (but shortcut so that we don't // fall into a trap of finding a secondary element which wasn't the originally signed one). XmlNodeList nodeList = document.SelectNodes(xPath); if (nodeList == null || nodeList.Count == 0) { return null; } if (nodeList.Count == 1) { return nodeList[0] as XmlElement; } throw new CryptographicException(SR.Cryptography_Xml_InvalidReference); } private static bool IsKeyTheCorrectAlgorithm(AsymmetricAlgorithm key, Type expectedType) { Type actualType = key.GetType(); if (actualType == expectedType) return true; // This check exists solely for compatibility with 4.6. Normally, we would expect "expectedType" to be the superclass type and // the actualType to be the subclass. if (expectedType.IsSubclassOf(actualType)) return true; // // "expectedType" comes from the KeyAlgorithm property of a SignatureDescription. The BCL SignatureDescription classes have historically // denoted provider-specific implementations ("RSACryptoServiceProvider") rather than the base class for the algorithm ("RSA"). We could // change those (at the risk of creating other compat problems) but we have no control over third party SignatureDescriptions. // // So, in the absence of a better approach, walk up the parent hierarchy until we find the ancestor that's a direct subclass of // AsymmetricAlgorithm and treat that as the algorithm identifier. // while (expectedType != null && expectedType.BaseType != typeof(AsymmetricAlgorithm)) { expectedType = expectedType.BaseType; } if (expectedType == null) return false; // SignatureDescription specified something that isn't even a subclass of AsymmetricAlgorithm. For compatibility with 4.6, return false rather throw. if (actualType.IsSubclassOf(expectedType)) return true; return false; } } }
using System; using System.Collections; using Org.BouncyCastle.Asn1.X500; using Org.BouncyCastle.Math; namespace Org.BouncyCastle.Asn1.X509.SigI { /** * Contains personal data for the otherName field in the subjectAltNames * extension. * <p/> * <pre> * PersonalData ::= SEQUENCE { * nameOrPseudonym NameOrPseudonym, * nameDistinguisher [0] INTEGER OPTIONAL, * dateOfBirth [1] GeneralizedTime OPTIONAL, * placeOfBirth [2] DirectoryString OPTIONAL, * gender [3] PrintableString OPTIONAL, * postalAddress [4] DirectoryString OPTIONAL * } * </pre> * * @see org.bouncycastle.asn1.x509.sigi.NameOrPseudonym * @see org.bouncycastle.asn1.x509.sigi.SigIObjectIdentifiers */ public class PersonalData : Asn1Encodable { private readonly NameOrPseudonym nameOrPseudonym; private readonly BigInteger nameDistinguisher; private readonly DerGeneralizedTime dateOfBirth; private readonly DirectoryString placeOfBirth; private readonly string gender; private readonly DirectoryString postalAddress; public static PersonalData GetInstance( object obj) { if (obj == null || obj is PersonalData) { return (PersonalData) obj; } if (obj is Asn1Sequence) { return new PersonalData((Asn1Sequence) obj); } throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); } /** * Constructor from Asn1Sequence. * <p/> * The sequence is of type NameOrPseudonym: * <p/> * <pre> * PersonalData ::= SEQUENCE { * nameOrPseudonym NameOrPseudonym, * nameDistinguisher [0] INTEGER OPTIONAL, * dateOfBirth [1] GeneralizedTime OPTIONAL, * placeOfBirth [2] DirectoryString OPTIONAL, * gender [3] PrintableString OPTIONAL, * postalAddress [4] DirectoryString OPTIONAL * } * </pre> * * @param seq The ASN.1 sequence. */ private PersonalData( Asn1Sequence seq) { if (seq.Count < 1) throw new ArgumentException("Bad sequence size: " + seq.Count); IEnumerator e = seq.GetEnumerator(); e.MoveNext(); nameOrPseudonym = NameOrPseudonym.GetInstance(e.Current); while (e.MoveNext()) { Asn1TaggedObject o = Asn1TaggedObject.GetInstance(e.Current); int tag = o.TagNo; switch (tag) { case 0: nameDistinguisher = DerInteger.GetInstance(o, false).Value; break; case 1: dateOfBirth = DerGeneralizedTime.GetInstance(o, false); break; case 2: placeOfBirth = DirectoryString.GetInstance(o, true); break; case 3: gender = DerPrintableString.GetInstance(o, false).GetString(); break; case 4: postalAddress = DirectoryString.GetInstance(o, true); break; default: throw new ArgumentException("Bad tag number: " + o.TagNo); } } } /** * Constructor from a given details. * * @param nameOrPseudonym Name or pseudonym. * @param nameDistinguisher Name distinguisher. * @param dateOfBirth Date of birth. * @param placeOfBirth Place of birth. * @param gender Gender. * @param postalAddress Postal Address. */ public PersonalData( NameOrPseudonym nameOrPseudonym, BigInteger nameDistinguisher, DerGeneralizedTime dateOfBirth, DirectoryString placeOfBirth, string gender, DirectoryString postalAddress) { this.nameOrPseudonym = nameOrPseudonym; this.dateOfBirth = dateOfBirth; this.gender = gender; this.nameDistinguisher = nameDistinguisher; this.postalAddress = postalAddress; this.placeOfBirth = placeOfBirth; } public NameOrPseudonym NameOrPseudonym { get { return nameOrPseudonym; } } public BigInteger NameDistinguisher { get { return nameDistinguisher; } } public DerGeneralizedTime DateOfBirth { get { return dateOfBirth; } } public DirectoryString PlaceOfBirth { get { return placeOfBirth; } } public string Gender { get { return gender; } } public DirectoryString PostalAddress { get { return postalAddress; } } /** * Produce an object suitable for an Asn1OutputStream. * <p/> * Returns: * <p/> * <pre> * PersonalData ::= SEQUENCE { * nameOrPseudonym NameOrPseudonym, * nameDistinguisher [0] INTEGER OPTIONAL, * dateOfBirth [1] GeneralizedTime OPTIONAL, * placeOfBirth [2] DirectoryString OPTIONAL, * gender [3] PrintableString OPTIONAL, * postalAddress [4] DirectoryString OPTIONAL * } * </pre> * * @return an Asn1Object */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector vec = new Asn1EncodableVector(); vec.Add(nameOrPseudonym); if (nameDistinguisher != null) { vec.Add(new DerTaggedObject(false, 0, new DerInteger(nameDistinguisher))); } if (dateOfBirth != null) { vec.Add(new DerTaggedObject(false, 1, dateOfBirth)); } if (placeOfBirth != null) { vec.Add(new DerTaggedObject(true, 2, placeOfBirth)); } if (gender != null) { vec.Add(new DerTaggedObject(false, 3, new DerPrintableString(gender, true))); } if (postalAddress != null) { vec.Add(new DerTaggedObject(true, 4, postalAddress)); } return new DerSequence(vec); } } }
using J2N; using J2N.Collections.Generic.Extensions; using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.Text; using JCG = J2N.Collections.Generic; /* * dk.brics.automaton * * Copyright (c) 2001-2009 Anders Moeller * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * this SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 Lucene.Net.Util.Automaton { /// <summary> /// Finite-state automaton with regular expression operations. /// <para/> /// Class invariants: /// <list type="bullet"> /// <item><description>An automaton is either represented explicitly (with <see cref="State"/> and /// <see cref="Transition"/> objects) or with a singleton string (see /// <see cref="Singleton"/> and <see cref="ExpandSingleton()"/>) in case the automaton /// is known to accept exactly one string. (Implicitly, all states and /// transitions of an automaton are reachable from its initial state.)</description></item> /// <item><description>Automata are always reduced (see <see cref="Reduce()"/>) and have no /// transitions to dead states (see <see cref="RemoveDeadTransitions()"/>).</description></item> /// <item><description>If an automaton is nondeterministic, then <see cref="IsDeterministic"/> /// returns <c>false</c> (but the converse is not required).</description></item> /// <item><description>Automata provided as input to operations are generally assumed to be /// disjoint.</description></item> /// </list> /// <para/> /// If the states or transitions are manipulated manually, the /// <see cref="RestoreInvariant()"/> method and <see cref="IsDeterministic"/> setter /// should be used afterwards to restore representation invariants that are /// assumed by the built-in automata operations. /// /// <para/> /// <para> /// Note: this class has internal mutable state and is not thread safe. It is /// the caller's responsibility to ensure any necessary synchronization if you /// wish to use the same Automaton from multiple threads. In general it is instead /// recommended to use a <see cref="RunAutomaton"/> for multithreaded matching: it is immutable, /// thread safe, and much faster. /// </para> /// @lucene.experimental /// </summary> public class Automaton #if FEATURE_CLONEABLE : System.ICloneable #endif { /// <summary> /// Minimize using Hopcroft's O(n log n) algorithm. this is regarded as one of /// the most generally efficient algorithms that exist. /// </summary> /// <seealso cref="SetMinimization(int)"/> public const int MINIMIZE_HOPCROFT = 2; /// <summary> /// Selects minimization algorithm (default: <c>MINIMIZE_HOPCROFT</c>). </summary> internal static int minimization = MINIMIZE_HOPCROFT; /// <summary> /// Initial state of this automaton. </summary> internal State initial; /// <summary> /// If <c>true</c>, then this automaton is definitely deterministic (i.e., there are /// no choices for any run, but a run may crash). /// </summary> internal bool deterministic; /// <summary> /// Extra data associated with this automaton. </summary> internal object info; ///// <summary> ///// Hash code. Recomputed by <see cref="MinimizationOperations#minimize(Automaton)"/> ///// </summary> //int hash_code; /// <summary> /// Singleton string. Null if not applicable. </summary> internal string singleton; /// <summary> /// Minimize always flag. </summary> internal static bool minimize_always = false; /// <summary> /// Selects whether operations may modify the input automata (default: /// <c>false</c>). /// </summary> internal static bool allow_mutation = false; /// <summary> /// Constructs a new automaton that accepts the empty language. Using this /// constructor, automata can be constructed manually from <see cref="State"/> and /// <see cref="Transition"/> objects. /// </summary> /// <seealso cref="State"/> /// <seealso cref="Transition"/> public Automaton(State initial) { this.initial = initial; deterministic = true; singleton = null; } public Automaton() : this(new State()) { } /// <summary> /// Selects minimization algorithm (default: <c>MINIMIZE_HOPCROFT</c>). /// </summary> /// <param name="algorithm"> minimization algorithm </param> public static void SetMinimization(int algorithm) { minimization = algorithm; } /// <summary> /// Sets or resets minimize always flag. If this flag is set, then /// <see cref="MinimizationOperations.Minimize(Automaton)"/> will automatically be /// invoked after all operations that otherwise may produce non-minimal /// automata. By default, the flag is not set. /// </summary> /// <param name="flag"> if <c>true</c>, the flag is set </param> public static void SetMinimizeAlways(bool flag) { minimize_always = flag; } /// <summary> /// Sets or resets allow mutate flag. If this flag is set, then all automata /// operations may modify automata given as input; otherwise, operations will /// always leave input automata languages unmodified. By default, the flag is /// not set. /// </summary> /// <param name="flag"> if <c>true</c>, the flag is set </param> /// <returns> previous value of the flag </returns> public static bool SetAllowMutate(bool flag) { bool b = allow_mutation; allow_mutation = flag; return b; } /// <summary> /// Returns the state of the allow mutate flag. If this flag is set, then all /// automata operations may modify automata given as input; otherwise, /// operations will always leave input automata languages unmodified. By /// default, the flag is not set. /// </summary> /// <returns> current value of the flag </returns> internal static bool AllowMutate => allow_mutation; internal virtual void CheckMinimizeAlways() { if (minimize_always) { MinimizationOperations.Minimize(this); } } internal bool IsSingleton => singleton != null; /// <summary> /// Returns the singleton string for this automaton. An automaton that accepts /// exactly one string <i>may</i> be represented in singleton mode. In that /// case, this method may be used to obtain the string. /// </summary> /// <returns> String, <c>null</c> if this automaton is not in singleton mode. </returns> public virtual string Singleton => singleton; ///// <summary> ///// Sets initial state. ///// </summary> ///// <param name="s"> state </param> /* public void setInitialState(State s) { initial = s; singleton = null; } */ /// <summary> /// Gets initial state. /// </summary> /// <returns> state </returns> public virtual State GetInitialState() { ExpandSingleton(); return initial; } /// <summary> /// Returns deterministic flag for this automaton. /// </summary> /// <returns> <c>true</c> if the automaton is definitely deterministic, <c>false</c> if the /// automaton may be nondeterministic </returns> public virtual bool IsDeterministic { get => deterministic; set => deterministic = value; } /// <summary> /// Associates extra information with this automaton. /// </summary> /// <param name="value"> extra information </param> public virtual object Info { get => info; set => info = value; } // cached private State[] numberedStates; public virtual State[] GetNumberedStates() { if (numberedStates == null) { ExpandSingleton(); JCG.HashSet<State> visited = new JCG.HashSet<State>(); Queue<State> worklist = new Queue<State>(); // LUCENENET specific - Queue is much more performant than LinkedList State[] states = new State[4]; int upto = 0; worklist.Enqueue(initial); visited.Add(initial); initial.number = upto; states[upto] = initial; upto++; while (worklist.Count > 0) { State s = worklist.Dequeue(); for (int i = 0; i < s.numTransitions; i++) { Transition t = s.TransitionsArray[i]; if (!visited.Contains(t.to)) { visited.Add(t.to); worklist.Enqueue(t.to); t.to.number = upto; if (upto == states.Length) { // LUCENENET: Resize rather than copy Array.Resize(ref states, ArrayUtil.Oversize(1 + upto, RamUsageEstimator.NUM_BYTES_OBJECT_REF)); } states[upto] = t.to; upto++; } } } if (states.Length != upto) { // LUCENENET: Resize rather than copy Array.Resize(ref states, upto); } numberedStates = states; } return numberedStates; } public virtual void SetNumberedStates(State[] states) { SetNumberedStates(states, states.Length); } public virtual void SetNumberedStates(State[] states, int count) { if (Debugging.AssertsEnabled) Debugging.Assert(count <= states.Length); // TODO: maybe we can eventually allow for oversizing here... if (count < states.Length) { State[] newArray = new State[count]; Array.Copy(states, 0, newArray, 0, count); numberedStates = newArray; } else { numberedStates = states; } } public virtual void ClearNumberedStates() { numberedStates = null; } /// <summary> /// Returns the set of reachable accept states. /// </summary> /// <returns> Set of <see cref="State"/> objects. </returns> public virtual ISet<State> GetAcceptStates() { ExpandSingleton(); JCG.HashSet<State> accepts = new JCG.HashSet<State>(); JCG.HashSet<State> visited = new JCG.HashSet<State>(); Queue<State> worklist = new Queue<State>(); // LUCENENET specific - Queue is much more performant than LinkedList worklist.Enqueue(initial); visited.Add(initial); while (worklist.Count > 0) { State s = worklist.Dequeue(); if (s.accept) { accepts.Add(s); } foreach (Transition t in s.GetTransitions()) { if (!visited.Contains(t.to)) { visited.Add(t.to); worklist.Enqueue(t.to); } } } return accepts; } /// <summary> /// Adds transitions to explicit crash state to ensure that transition function /// is total. /// </summary> internal virtual void Totalize() { State s = new State(); s.AddTransition(new Transition(Character.MinCodePoint, Character.MaxCodePoint, s)); foreach (State p in GetNumberedStates()) { int maxi = Character.MinCodePoint; p.SortTransitions(Transition.COMPARE_BY_MIN_MAX_THEN_DEST); foreach (Transition t in p.GetTransitions()) { if (t.min > maxi) { p.AddTransition(new Transition(maxi, (t.min - 1), s)); } if (t.max + 1 > maxi) { maxi = t.max + 1; } } if (maxi <= Character.MaxCodePoint) { p.AddTransition(new Transition(maxi, Character.MaxCodePoint, s)); } } ClearNumberedStates(); } /// <summary> /// Restores representation invariant. This method must be invoked before any /// built-in automata operation is performed if automaton states or transitions /// are manipulated manually. /// </summary> /// <seealso cref="IsDeterministic"/> public virtual void RestoreInvariant() { RemoveDeadTransitions(); } /// <summary> /// Reduces this automaton. An automaton is "reduced" by combining overlapping /// and adjacent edge intervals with same destination. /// </summary> public virtual void Reduce() { State[] states = GetNumberedStates(); if (IsSingleton) { return; } foreach (State s in states) { s.Reduce(); } } /// <summary> /// Returns sorted array of all interval start points. /// </summary> public virtual int[] GetStartPoints() { State[] states = GetNumberedStates(); JCG.HashSet<int> pointset = new JCG.HashSet<int> { Character.MinCodePoint }; foreach (State s in states) { foreach (Transition t in s.GetTransitions()) { pointset.Add(t.min); if (t.max < Character.MaxCodePoint) { pointset.Add((t.max + 1)); } } } int[] points = new int[pointset.Count]; int n = 0; foreach (int m in pointset) { points[n++] = m; } Array.Sort(points); return points; } /// <summary> /// Returns the set of live states. A state is "live" if an accept state is /// reachable from it. /// </summary> /// <returns> Set of <see cref="State"/> objects. </returns> private State[] GetLiveStates() { State[] states = GetNumberedStates(); JCG.HashSet<State> live = new JCG.HashSet<State>(); foreach (State q in states) { if (q.Accept) { live.Add(q); } } // map<state, set<state>> ISet<State>[] map = new JCG.HashSet<State>[states.Length]; for (int i = 0; i < map.Length; i++) { map[i] = new JCG.HashSet<State>(); } foreach (State s in states) { for (int i = 0; i < s.numTransitions; i++) { map[s.TransitionsArray[i].to.Number].Add(s); } } LinkedList<State> worklist = new LinkedList<State>(live); // LUCENENET: Queue would be slower in this case because of the copy constructor while (worklist.Count > 0) { State s = worklist.First.Value; worklist.Remove(s); foreach (State p in map[s.number]) { if (!live.Contains(p)) { live.Add(p); worklist.AddLast(p); } } } return live.ToArray(/*new State[live.Count]*/); } /// <summary> /// Removes transitions to dead states and calls <see cref="Reduce()"/>. /// (A state is "dead" if no accept state is /// reachable from it.) /// </summary> public virtual void RemoveDeadTransitions() { State[] states = GetNumberedStates(); //clearHashCode(); if (IsSingleton) { return; } State[] live = GetLiveStates(); OpenBitSet liveSet = new OpenBitSet(states.Length); foreach (State s in live) { liveSet.Set(s.number); } foreach (State s in states) { // filter out transitions to dead states: int upto = 0; for (int i = 0; i < s.numTransitions; i++) { Transition t = s.TransitionsArray[i]; if (liveSet.Get(t.to.number)) { s.TransitionsArray[upto++] = s.TransitionsArray[i]; } } s.numTransitions = upto; } for (int i = 0; i < live.Length; i++) { live[i].number = i; } if (live.Length > 0) { SetNumberedStates(live); } else { // sneaky corner case -- if machine accepts no strings ClearNumberedStates(); } Reduce(); } /// <summary> /// Returns a sorted array of transitions for each state (and sets state /// numbers). /// </summary> public virtual Transition[][] GetSortedTransitions() { State[] states = GetNumberedStates(); Transition[][] transitions = new Transition[states.Length][]; foreach (State s in states) { s.SortTransitions(Transition.COMPARE_BY_MIN_MAX_THEN_DEST); s.TrimTransitionsArray(); transitions[s.number] = s.TransitionsArray; if (Debugging.AssertsEnabled) Debugging.Assert(s.TransitionsArray != null); } return transitions; } /// <summary> /// Expands singleton representation to normal representation. Does nothing if /// not in singleton representation. /// </summary> public virtual void ExpandSingleton() { if (IsSingleton) { State p = new State(); initial = p; int cp; // LUCENENET: Removed unnecessary assignment for (int i = 0; i < singleton.Length; i += Character.CharCount(cp)) { State q = new State(); p.AddTransition(new Transition(cp = Character.CodePointAt(singleton, i), q)); p = q; } p.accept = true; deterministic = true; singleton = null; } } /// <summary> /// Returns the number of states in this automaton. /// </summary> public virtual int GetNumberOfStates() { if (IsSingleton) { return singleton.CodePointCount(0, singleton.Length) + 1; } return GetNumberedStates().Length; } /// <summary> /// Returns the number of transitions in this automaton. This number is counted /// as the total number of edges, where one edge may be a character interval. /// </summary> public virtual int GetNumberOfTransitions() { if (IsSingleton) { return singleton.CodePointCount(0, singleton.Length); } int c = 0; foreach (State s in GetNumberedStates()) { c += s.NumTransitions; } return c; } public override bool Equals(object obj) { var other = obj as Automaton; return BasicOperations.SameLanguage(this, other); //throw new NotSupportedException("use BasicOperations.sameLanguage instead"); } // LUCENENET specific - in .NET, we can't simply throw an exception here because // collections use this to determine equality. Most of this code was pieced together from // BasicOperations.SubSetOf (which, when done both ways determines equality). public override int GetHashCode() { if (IsSingleton) { return singleton.GetHashCode(); } int hash = 31; // arbitrary prime this.Determinize(); // LUCENENET: should we do this ? Transition[][] transitions = this.GetSortedTransitions(); Queue<State> worklist = new Queue<State>(); // LUCENENET specific - Queue is much more performant than LinkedList JCG.HashSet<State> visited = new JCG.HashSet<State>(); State current; worklist.Enqueue(this.initial); visited.Add(this.initial); while (worklist.Count > 0) { current = worklist.Dequeue(); hash = 31 * hash + current.accept.GetHashCode(); Transition[] t1 = transitions[current.number]; for (int n1 = 0; n1 < t1.Length; n1++) { int min1 = t1[n1].min, max1 = t1[n1].max; hash = 31 * hash + min1.GetHashCode(); hash = 31 * hash + max1.GetHashCode(); State next = t1[n1].to; if (!visited.Contains(next)) { worklist.Enqueue(next); visited.Add(next); } } } return hash; //throw new NotSupportedException(); } ///// <summary> ///// Must be invoked when the stored hash code may no longer be valid. ///// </summary> /* void clearHashCode() { hash_code = 0; } */ /// <summary> /// Returns a string representation of this automaton. /// </summary> public override string ToString() { StringBuilder b = new StringBuilder(); if (IsSingleton) { b.Append("singleton: "); int length = singleton.CodePointCount(0, singleton.Length); int[] codepoints = new int[length]; int cp; // LUCENENET: Removed unnecessary assignment for (int i = 0, j = 0; i < singleton.Length; i += Character.CharCount(cp)) { codepoints[j++] = cp = singleton.CodePointAt(i); } foreach (int c in codepoints) { Transition.AppendCharString(c, b); } b.Append("\n"); } else { State[] states = GetNumberedStates(); b.Append("initial state: ").Append(initial.number).Append("\n"); foreach (State s in states) { b.Append(s.ToString()); } } return b.ToString(); } /// <summary> /// Returns <a href="http://www.research.att.com/sw/tools/graphviz/" /// target="_top">Graphviz Dot</a> representation of this automaton. /// </summary> public virtual string ToDot() { StringBuilder b = new StringBuilder("digraph Automaton {\n"); b.Append(" rankdir = LR;\n"); State[] states = GetNumberedStates(); foreach (State s in states) { b.Append(" ").Append(s.number); if (s.accept) { b.Append(" [shape=doublecircle,label=\"\"];\n"); } else { b.Append(" [shape=circle,label=\"\"];\n"); } if (s == initial) { b.Append(" initial [shape=plaintext,label=\"\"];\n"); b.Append(" initial -> ").Append(s.number).Append("\n"); } foreach (Transition t in s.GetTransitions()) { b.Append(" ").Append(s.number); t.AppendDot(b); } } return b.Append("}\n").ToString(); } /// <summary> /// Returns a clone of this automaton, expands if singleton. /// </summary> internal virtual Automaton CloneExpanded() { Automaton a = (Automaton)Clone(); a.ExpandSingleton(); return a; } /// <summary> /// Returns a clone of this automaton unless <see cref="allow_mutation"/> is /// set, expands if singleton. /// </summary> internal virtual Automaton CloneExpandedIfRequired() { if (allow_mutation) { ExpandSingleton(); return this; } else { return CloneExpanded(); } } /// <summary> /// Returns a clone of this automaton. /// </summary> public virtual object Clone() { Automaton a = (Automaton)base.MemberwiseClone(); if (!IsSingleton) { Dictionary<State, State> m = new Dictionary<State, State>(); State[] states = GetNumberedStates(); foreach (State s in states) { m[s] = new State(); } foreach (State s in states) { State p = m[s]; p.accept = s.accept; if (s == initial) { a.initial = p; } foreach (Transition t in s.GetTransitions()) { p.AddTransition(new Transition(t.min, t.max, m[t.to])); } } } a.ClearNumberedStates(); return a; } /// <summary> /// Returns a clone of this automaton, or this automaton itself if /// <see cref="allow_mutation"/> flag is set. /// </summary> internal virtual Automaton CloneIfRequired() { if (allow_mutation) { return this; } else { return (Automaton)Clone(); } } /// <summary> /// See <see cref="BasicOperations.Concatenate(Automaton, Automaton)"/>. /// </summary> public virtual Automaton Concatenate(Automaton a) { return BasicOperations.Concatenate(this, a); } /// <summary> /// See <see cref="BasicOperations.Concatenate(IList{Automaton})"/>. /// </summary> public static Automaton Concatenate(IList<Automaton> l) { return BasicOperations.Concatenate(l); } /// <summary> /// See <see cref="BasicOperations.Optional(Automaton)"/>. /// </summary> public virtual Automaton Optional() { return BasicOperations.Optional(this); } /// <summary> /// See <see cref="BasicOperations.Repeat(Automaton)"/>. /// </summary> public virtual Automaton Repeat() { return BasicOperations.Repeat(this); } /// <summary> /// See <see cref="BasicOperations.Repeat(Automaton, int)"/>. /// </summary> public virtual Automaton Repeat(int min) { return BasicOperations.Repeat(this, min); } /// <summary> /// See <see cref="BasicOperations.Repeat(Automaton, int, int)"/>. /// </summary> public virtual Automaton Repeat(int min, int max) { return BasicOperations.Repeat(this, min, max); } /// <summary> /// See <see cref="BasicOperations.Complement(Automaton)"/>. /// </summary> public virtual Automaton Complement() { return BasicOperations.Complement(this); } /// <summary> /// See <see cref="BasicOperations.Minus(Automaton, Automaton)"/>. /// </summary> public virtual Automaton Minus(Automaton a) { return BasicOperations.Minus(this, a); } /// <summary> /// See <see cref="BasicOperations.Intersection(Automaton, Automaton)"/>. /// </summary> public virtual Automaton Intersection(Automaton a) { return BasicOperations.Intersection(this, a); } /// <summary> /// See <see cref="BasicOperations.SubsetOf(Automaton, Automaton)"/>. /// </summary> public virtual bool SubsetOf(Automaton a) { return BasicOperations.SubsetOf(this, a); } /// <summary> /// See <see cref="BasicOperations.Union(Automaton, Automaton)"/>. /// </summary> public virtual Automaton Union(Automaton a) { return BasicOperations.Union(this, a); } /// <summary> /// See <see cref="BasicOperations.Union(ICollection{Automaton})"/>. /// </summary> public static Automaton Union(ICollection<Automaton> l) { return BasicOperations.Union(l); } /// <summary> /// See <see cref="BasicOperations.Determinize(Automaton)"/>. /// </summary> public virtual void Determinize() { BasicOperations.Determinize(this); } /// <summary> /// See <see cref="BasicOperations.IsEmptyString(Automaton)"/>. /// </summary> public virtual bool IsEmptyString => BasicOperations.IsEmptyString(this); /// <summary> /// See <see cref="MinimizationOperations.Minimize(Automaton)"/>. Returns the /// automaton being given as argument. /// </summary> public static Automaton Minimize(Automaton a) { MinimizationOperations.Minimize(a); return a; } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace ME.Kevingleason.Pnwebrtc { // Metadata.xml XPath class reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnSignalingParams']" [global::Android.Runtime.Register ("me/kevingleason/pnwebrtc/PnSignalingParams", DoNotGenerateAcw=true)] public partial class PnSignalingParams : global::Java.Lang.Object { static IntPtr audioConstraints_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnSignalingParams']/field[@name='audioConstraints']" [Register ("audioConstraints")] public global::Org.Webrtc.MediaConstraints AudioConstraints { get { if (audioConstraints_jfieldId == IntPtr.Zero) audioConstraints_jfieldId = JNIEnv.GetFieldID (class_ref, "audioConstraints", "Lorg/webrtc/MediaConstraints;"); IntPtr __ret = JNIEnv.GetObjectField (Handle, audioConstraints_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaConstraints> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (audioConstraints_jfieldId == IntPtr.Zero) audioConstraints_jfieldId = JNIEnv.GetFieldID (class_ref, "audioConstraints", "Lorg/webrtc/MediaConstraints;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); try { JNIEnv.SetField (Handle, audioConstraints_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr iceServers_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnSignalingParams']/field[@name='iceServers']" [Register ("iceServers")] public global::System.Collections.IList IceServers { get { if (iceServers_jfieldId == IntPtr.Zero) iceServers_jfieldId = JNIEnv.GetFieldID (class_ref, "iceServers", "Ljava/util/List;"); IntPtr __ret = JNIEnv.GetObjectField (Handle, iceServers_jfieldId); return global::Android.Runtime.JavaList.FromJniHandle (__ret, JniHandleOwnership.TransferLocalRef); } set { if (iceServers_jfieldId == IntPtr.Zero) iceServers_jfieldId = JNIEnv.GetFieldID (class_ref, "iceServers", "Ljava/util/List;"); IntPtr native_value = global::Android.Runtime.JavaList.ToLocalJniHandle (value); try { JNIEnv.SetField (Handle, iceServers_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr pcConstraints_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnSignalingParams']/field[@name='pcConstraints']" [Register ("pcConstraints")] public global::Org.Webrtc.MediaConstraints PcConstraints { get { if (pcConstraints_jfieldId == IntPtr.Zero) pcConstraints_jfieldId = JNIEnv.GetFieldID (class_ref, "pcConstraints", "Lorg/webrtc/MediaConstraints;"); IntPtr __ret = JNIEnv.GetObjectField (Handle, pcConstraints_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaConstraints> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (pcConstraints_jfieldId == IntPtr.Zero) pcConstraints_jfieldId = JNIEnv.GetFieldID (class_ref, "pcConstraints", "Lorg/webrtc/MediaConstraints;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); try { JNIEnv.SetField (Handle, pcConstraints_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } static IntPtr videoConstraints_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnSignalingParams']/field[@name='videoConstraints']" [Register ("videoConstraints")] public global::Org.Webrtc.MediaConstraints VideoConstraints { get { if (videoConstraints_jfieldId == IntPtr.Zero) videoConstraints_jfieldId = JNIEnv.GetFieldID (class_ref, "videoConstraints", "Lorg/webrtc/MediaConstraints;"); IntPtr __ret = JNIEnv.GetObjectField (Handle, videoConstraints_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaConstraints> (__ret, JniHandleOwnership.TransferLocalRef); } set { if (videoConstraints_jfieldId == IntPtr.Zero) videoConstraints_jfieldId = JNIEnv.GetFieldID (class_ref, "videoConstraints", "Lorg/webrtc/MediaConstraints;"); IntPtr native_value = JNIEnv.ToLocalJniHandle (value); try { JNIEnv.SetField (Handle, videoConstraints_jfieldId, native_value); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("me/kevingleason/pnwebrtc/PnSignalingParams", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (PnSignalingParams); } } protected PnSignalingParams (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_; // Metadata.xml XPath constructor reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnSignalingParams']/constructor[@name='PnSignalingParams' and count(parameter)=3 and parameter[1][@type='org.webrtc.MediaConstraints'] and parameter[2][@type='org.webrtc.MediaConstraints'] and parameter[3][@type='org.webrtc.MediaConstraints']]" [Register (".ctor", "(Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;)V", "")] public unsafe PnSignalingParams (global::Org.Webrtc.MediaConstraints p0, global::Org.Webrtc.MediaConstraints p1, global::Org.Webrtc.MediaConstraints p2) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [3]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); __args [2] = new JValue (p2); if (GetType () != typeof (PnSignalingParams)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;)V", __args); return; } if (id_ctor_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_ == IntPtr.Zero) id_ctor_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_, __args); } finally { } } static IntPtr id_ctor_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_; // Metadata.xml XPath constructor reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnSignalingParams']/constructor[@name='PnSignalingParams' and count(parameter)=4 and parameter[1][@type='java.util.List&lt;org.webrtc.PeerConnection.IceServer&gt;'] and parameter[2][@type='org.webrtc.MediaConstraints'] and parameter[3][@type='org.webrtc.MediaConstraints'] and parameter[4][@type='org.webrtc.MediaConstraints']]" [Register (".ctor", "(Ljava/util/List;Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;)V", "")] public unsafe PnSignalingParams (global::System.Collections.Generic.IList<global::Org.Webrtc.PeerConnection.IceServer> p0, global::Org.Webrtc.MediaConstraints p1, global::Org.Webrtc.MediaConstraints p2, global::Org.Webrtc.MediaConstraints p3) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; IntPtr native_p0 = global::Android.Runtime.JavaList<global::Org.Webrtc.PeerConnection.IceServer>.ToLocalJniHandle (p0); try { JValue* __args = stackalloc JValue [4]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); __args [2] = new JValue (p2); __args [3] = new JValue (p3); if (GetType () != typeof (PnSignalingParams)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Ljava/util/List;Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Ljava/util/List;Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;)V", __args); return; } if (id_ctor_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_ == IntPtr.Zero) id_ctor_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/util/List;Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;Lorg/webrtc/MediaConstraints;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Ljava_util_List_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_Lorg_webrtc_MediaConstraints_, __args); } finally { JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnSignalingParams']/constructor[@name='PnSignalingParams' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe PnSignalingParams () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { if (GetType () != typeof (PnSignalingParams)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor); } finally { } } static IntPtr id_ctor_Ljava_util_List_; // Metadata.xml XPath constructor reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnSignalingParams']/constructor[@name='PnSignalingParams' and count(parameter)=1 and parameter[1][@type='java.util.List&lt;org.webrtc.PeerConnection.IceServer&gt;']]" [Register (".ctor", "(Ljava/util/List;)V", "")] public unsafe PnSignalingParams (global::System.Collections.Generic.IList<global::Org.Webrtc.PeerConnection.IceServer> p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; IntPtr native_p0 = global::Android.Runtime.JavaList<global::Org.Webrtc.PeerConnection.IceServer>.ToLocalJniHandle (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); if (GetType () != typeof (PnSignalingParams)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Ljava/util/List;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Ljava/util/List;)V", __args); return; } if (id_ctor_Ljava_util_List_ == IntPtr.Zero) id_ctor_Ljava_util_List_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/util/List;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_util_List_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Ljava_util_List_, __args); } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_addIceServers_Ljava_util_List_; #pragma warning disable 0169 static Delegate GetAddIceServers_Ljava_util_List_Handler () { if (cb_addIceServers_Ljava_util_List_ == null) cb_addIceServers_Ljava_util_List_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_AddIceServers_Ljava_util_List_); return cb_addIceServers_Ljava_util_List_; } static void n_AddIceServers_Ljava_util_List_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::ME.Kevingleason.Pnwebrtc.PnSignalingParams __this = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnSignalingParams> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); var p0 = global::Android.Runtime.JavaList<global::Org.Webrtc.PeerConnection.IceServer>.FromJniHandle (native_p0, JniHandleOwnership.DoNotTransfer); __this.AddIceServers (p0); } #pragma warning restore 0169 static IntPtr id_addIceServers_Ljava_util_List_; // Metadata.xml XPath method reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnSignalingParams']/method[@name='addIceServers' and count(parameter)=1 and parameter[1][@type='java.util.List&lt;org.webrtc.PeerConnection.IceServer&gt;']]" [Register ("addIceServers", "(Ljava/util/List;)V", "GetAddIceServers_Ljava_util_List_Handler")] public virtual unsafe void AddIceServers (global::System.Collections.Generic.IList<global::Org.Webrtc.PeerConnection.IceServer> p0) { if (id_addIceServers_Ljava_util_List_ == IntPtr.Zero) id_addIceServers_Ljava_util_List_ = JNIEnv.GetMethodID (class_ref, "addIceServers", "(Ljava/util/List;)V"); IntPtr native_p0 = global::Android.Runtime.JavaList<global::Org.Webrtc.PeerConnection.IceServer>.ToLocalJniHandle (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_addIceServers_Ljava_util_List_, __args); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "addIceServers", "(Ljava/util/List;)V"), __args); } finally { JNIEnv.DeleteLocalRef (native_p0); } } static Delegate cb_addIceServers_Lorg_webrtc_PeerConnection_IceServer_; #pragma warning disable 0169 static Delegate GetAddIceServers_Lorg_webrtc_PeerConnection_IceServer_Handler () { if (cb_addIceServers_Lorg_webrtc_PeerConnection_IceServer_ == null) cb_addIceServers_Lorg_webrtc_PeerConnection_IceServer_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_AddIceServers_Lorg_webrtc_PeerConnection_IceServer_); return cb_addIceServers_Lorg_webrtc_PeerConnection_IceServer_; } static void n_AddIceServers_Lorg_webrtc_PeerConnection_IceServer_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::ME.Kevingleason.Pnwebrtc.PnSignalingParams __this = global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnSignalingParams> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.PeerConnection.IceServer p0 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.PeerConnection.IceServer> (native_p0, JniHandleOwnership.DoNotTransfer); __this.AddIceServers (p0); } #pragma warning restore 0169 static IntPtr id_addIceServers_Lorg_webrtc_PeerConnection_IceServer_; // Metadata.xml XPath method reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnSignalingParams']/method[@name='addIceServers' and count(parameter)=1 and parameter[1][@type='org.webrtc.PeerConnection.IceServer']]" [Register ("addIceServers", "(Lorg/webrtc/PeerConnection$IceServer;)V", "GetAddIceServers_Lorg_webrtc_PeerConnection_IceServer_Handler")] public virtual unsafe void AddIceServers (global::Org.Webrtc.PeerConnection.IceServer p0) { if (id_addIceServers_Lorg_webrtc_PeerConnection_IceServer_ == IntPtr.Zero) id_addIceServers_Lorg_webrtc_PeerConnection_IceServer_ = JNIEnv.GetMethodID (class_ref, "addIceServers", "(Lorg/webrtc/PeerConnection$IceServer;)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_addIceServers_Lorg_webrtc_PeerConnection_IceServer_, __args); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "addIceServers", "(Lorg/webrtc/PeerConnection$IceServer;)V"), __args); } finally { } } static IntPtr id_defaultIceServers; // Metadata.xml XPath method reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnSignalingParams']/method[@name='defaultIceServers' and count(parameter)=0]" [Register ("defaultIceServers", "()Ljava/util/List;", "")] public static unsafe global::System.Collections.Generic.IList<global::Org.Webrtc.PeerConnection.IceServer> DefaultIceServers () { if (id_defaultIceServers == IntPtr.Zero) id_defaultIceServers = JNIEnv.GetStaticMethodID (class_ref, "defaultIceServers", "()Ljava/util/List;"); try { return global::Android.Runtime.JavaList<global::Org.Webrtc.PeerConnection.IceServer>.FromJniHandle (JNIEnv.CallStaticObjectMethod (class_ref, id_defaultIceServers), JniHandleOwnership.TransferLocalRef); } finally { } } static IntPtr id_defaultInstance; // Metadata.xml XPath method reference: path="/api/package[@name='me.kevingleason.pnwebrtc']/class[@name='PnSignalingParams']/method[@name='defaultInstance' and count(parameter)=0]" [Register ("defaultInstance", "()Lme/kevingleason/pnwebrtc/PnSignalingParams;", "")] public static unsafe global::ME.Kevingleason.Pnwebrtc.PnSignalingParams DefaultInstance () { if (id_defaultInstance == IntPtr.Zero) id_defaultInstance = JNIEnv.GetStaticMethodID (class_ref, "defaultInstance", "()Lme/kevingleason/pnwebrtc/PnSignalingParams;"); try { return global::Java.Lang.Object.GetObject<global::ME.Kevingleason.Pnwebrtc.PnSignalingParams> (JNIEnv.CallStaticObjectMethod (class_ref, id_defaultInstance), JniHandleOwnership.TransferLocalRef); } finally { } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Buffers { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using DotNetty.Common.Utilities; enum SizeClass { Tiny, Small, Normal } abstract class PoolArena<T> : IPoolArenaMetric { internal static readonly int NumTinySubpagePools = 512 >> 4; internal readonly PooledByteBufferAllocator Parent; readonly int maxOrder; internal readonly int PageSize; internal readonly int PageShifts; internal readonly int ChunkSize; internal readonly int SubpageOverflowMask; internal readonly int NumSmallSubpagePools; readonly PoolSubpage<T>[] tinySubpagePools; readonly PoolSubpage<T>[] smallSubpagePools; readonly PoolChunkList<T> q050; readonly PoolChunkList<T> q025; readonly PoolChunkList<T> q000; readonly PoolChunkList<T> qInit; readonly PoolChunkList<T> q075; readonly PoolChunkList<T> q100; readonly List<IPoolChunkListMetric> chunkListMetrics; // Metrics for allocations and deallocations long allocationsTiny; long allocationsSmall; long allocationsNormal; // We need to use the LongCounter here as this is not guarded via synchronized block. long allocationsHuge; long activeBytesHuge; long deallocationsTiny; long deallocationsSmall; long deallocationsNormal; // We need to use the LongCounter here as this is not guarded via synchronized block. long deallocationsHuge; // Number of thread caches backed by this arena. int numThreadCaches; // TODO: Test if adding padding helps under contention //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; protected PoolArena(PooledByteBufferAllocator parent, int pageSize, int maxOrder, int pageShifts, int chunkSize) { this.Parent = parent; this.PageSize = pageSize; this.maxOrder = maxOrder; this.PageShifts = pageShifts; this.ChunkSize = chunkSize; this.SubpageOverflowMask = ~(pageSize - 1); this.tinySubpagePools = this.NewSubpagePoolArray(NumTinySubpagePools); for (int i = 0; i < this.tinySubpagePools.Length; i++) { this.tinySubpagePools[i] = this.NewSubpagePoolHead(pageSize); } this.NumSmallSubpagePools = pageShifts - 9; this.smallSubpagePools = this.NewSubpagePoolArray(this.NumSmallSubpagePools); for (int i = 0; i < this.smallSubpagePools.Length; i++) { this.smallSubpagePools[i] = this.NewSubpagePoolHead(pageSize); } this.q100 = new PoolChunkList<T>(null, 100, int.MaxValue, chunkSize); this.q075 = new PoolChunkList<T>(this.q100, 75, 100, chunkSize); this.q050 = new PoolChunkList<T>(this.q075, 50, 100, chunkSize); this.q025 = new PoolChunkList<T>(this.q050, 25, 75, chunkSize); this.q000 = new PoolChunkList<T>(this.q025, 1, 50, chunkSize); this.qInit = new PoolChunkList<T>(this.q000, int.MinValue, 25, chunkSize); this.q100.PrevList(this.q075); this.q075.PrevList(this.q050); this.q050.PrevList(this.q025); this.q025.PrevList(this.q000); this.q000.PrevList(null); this.qInit.PrevList(this.qInit); var metrics = new List<IPoolChunkListMetric>(6); metrics.Add(this.qInit); metrics.Add(this.q000); metrics.Add(this.q025); metrics.Add(this.q050); metrics.Add(this.q075); metrics.Add(this.q100); this.chunkListMetrics = metrics; } public int NumThreadCaches => Volatile.Read(ref this.numThreadCaches); public void RegisterThreadCache() => Interlocked.Increment(ref this.numThreadCaches); public void DeregisterThreadCache() => Interlocked.Decrement(ref this.numThreadCaches); PoolSubpage<T> NewSubpagePoolHead(int pageSize) { var head = new PoolSubpage<T>(pageSize); head.Prev = head; head.Next = head; return head; } PoolSubpage<T>[] NewSubpagePoolArray(int size) => new PoolSubpage<T>[size]; internal PooledByteBuffer<T> Allocate(PoolThreadCache<T> cache, int reqCapacity, int maxCapacity) { PooledByteBuffer<T> buf = this.NewByteBuf(maxCapacity); this.Allocate(cache, buf, reqCapacity); return buf; } internal static int TinyIdx(int normCapacity) => normCapacity.RightUShift(4); internal static int SmallIdx(int normCapacity) { int tableIdx = 0; int i = normCapacity.RightUShift(10); while (i != 0) { i = i.RightUShift(1); tableIdx++; } return tableIdx; } // capacity < pageSize internal bool IsTinyOrSmall(int normCapacity) => (normCapacity & this.SubpageOverflowMask) == 0; // normCapacity < 512 internal static bool IsTiny(int normCapacity) => (normCapacity & 0xFFFFFE00) == 0; void Allocate(PoolThreadCache<T> cache, PooledByteBuffer<T> buf, int reqCapacity) { int normCapacity = this.NormalizeCapacity(reqCapacity); if (this.IsTinyOrSmall(normCapacity)) { // capacity < pageSize int tableIdx; PoolSubpage<T>[] table; bool tiny = IsTiny(normCapacity); if (tiny) { // < 512 if (cache.AllocateTiny(this, buf, reqCapacity, normCapacity)) { // was able to allocate out of the cache so move on return; } tableIdx = TinyIdx(normCapacity); table = this.tinySubpagePools; } else { if (cache.AllocateSmall(this, buf, reqCapacity, normCapacity)) { // was able to allocate out of the cache so move on return; } tableIdx = SmallIdx(normCapacity); table = this.smallSubpagePools; } PoolSubpage<T> head = table[tableIdx]; /** * Synchronize on the head. This is needed as {@link PoolSubpage#allocate()} and * {@link PoolSubpage#free(int)} may modify the doubly linked list as well. */ lock (head) { PoolSubpage<T> s = head.Next; if (s != head) { Contract.Assert(s.DoNotDestroy && s.ElemSize == normCapacity); long handle = s.Allocate(); Contract.Assert(handle >= 0); s.Chunk.InitBufWithSubpage(buf, handle, reqCapacity); if (tiny) { ++this.allocationsTiny; } else { ++this.allocationsSmall; } return; } } this.AllocateNormal(buf, reqCapacity, normCapacity); return; } if (normCapacity <= this.ChunkSize) { if (cache.AllocateNormal(this, buf, reqCapacity, normCapacity)) { // was able to allocate out of the cache so move on return; } this.AllocateNormal(buf, reqCapacity, normCapacity); } else { // Huge allocations are never served via the cache so just call allocateHuge this.AllocateHuge(buf, reqCapacity); } } [MethodImpl(MethodImplOptions.Synchronized)] void AllocateNormal(PooledByteBuffer<T> buf, int reqCapacity, int normCapacity) { if (this.q050.Allocate(buf, reqCapacity, normCapacity) || this.q025.Allocate(buf, reqCapacity, normCapacity) || this.q000.Allocate(buf, reqCapacity, normCapacity) || this.qInit.Allocate(buf, reqCapacity, normCapacity) || this.q075.Allocate(buf, reqCapacity, normCapacity)) { ++this.allocationsNormal; return; } // Add a new chunk. PoolChunk<T> c = this.NewChunk(this.PageSize, this.maxOrder, this.PageShifts, this.ChunkSize); long handle = c.Allocate(normCapacity); ++this.allocationsNormal; Contract.Assert(handle > 0); c.InitBuf(buf, handle, reqCapacity); this.qInit.Add(c); } void AllocateHuge(PooledByteBuffer<T> buf, int reqCapacity) { PoolChunk<T> chunk = this.NewUnpooledChunk(reqCapacity); Interlocked.Add(ref this.activeBytesHuge, chunk.ChunkSize); buf.InitUnpooled(chunk, reqCapacity); Interlocked.Increment(ref this.allocationsHuge); } internal void Free(PoolChunk<T> chunk, long handle, int normCapacity, PoolThreadCache<T> cache) { if (chunk.Unpooled) { int size = chunk.ChunkSize; this.DestroyChunk(chunk); Interlocked.Add(ref this.activeBytesHuge, -size); Interlocked.Decrement(ref this.deallocationsHuge); } else { SizeClass sc = this.SizeClass(normCapacity); if (cache != null && cache.Add(this, chunk, handle, normCapacity, sc)) { // cached so not free it. return; } this.FreeChunk(chunk, handle, sc); } } SizeClass SizeClass(int normCapacity) { if (!this.IsTinyOrSmall(normCapacity)) { return Buffers.SizeClass.Normal; } return IsTiny(normCapacity) ? Buffers.SizeClass.Tiny : Buffers.SizeClass.Small; } internal void FreeChunk(PoolChunk<T> chunk, long handle, SizeClass sizeClass) { bool mustDestroyChunk; lock (this) { switch (sizeClass) { case Buffers.SizeClass.Normal: ++this.deallocationsNormal; break; case Buffers.SizeClass.Small: ++this.deallocationsSmall; break; case Buffers.SizeClass.Tiny: ++this.deallocationsTiny; break; default: throw new ArgumentOutOfRangeException(); } mustDestroyChunk = !chunk.Parent.Free(chunk, handle); } if (mustDestroyChunk) { // destroyChunk not need to be called while holding the synchronized lock. this.DestroyChunk(chunk); } } internal PoolSubpage<T> FindSubpagePoolHead(int elemSize) { int tableIdx; PoolSubpage<T>[] table; if (IsTiny(elemSize)) { // < 512 tableIdx = elemSize.RightUShift(4); table = this.tinySubpagePools; } else { tableIdx = 0; elemSize = elemSize.RightUShift(10); while (elemSize != 0) { elemSize = elemSize.RightUShift(1); tableIdx++; } table = this.smallSubpagePools; } return table[tableIdx]; } internal int NormalizeCapacity(int reqCapacity) { Contract.Requires(reqCapacity >= 0); if (reqCapacity >= this.ChunkSize) { return reqCapacity; } if (!IsTiny(reqCapacity)) { // >= 512 // Doubled int normalizedCapacity = reqCapacity; normalizedCapacity--; normalizedCapacity |= normalizedCapacity.RightUShift(1); normalizedCapacity |= normalizedCapacity.RightUShift(2); normalizedCapacity |= normalizedCapacity.RightUShift(4); normalizedCapacity |= normalizedCapacity.RightUShift(8); normalizedCapacity |= normalizedCapacity.RightUShift(16); normalizedCapacity++; if (normalizedCapacity < 0) { normalizedCapacity = normalizedCapacity.RightUShift(1); } return normalizedCapacity; } // Quantum-spaced if ((reqCapacity & 15) == 0) { return reqCapacity; } return (reqCapacity & ~15) + 16; } internal void Reallocate(PooledByteBuffer<T> buf, int newCapacity, bool freeOldMemory) { Contract.Requires(newCapacity >= 0 && newCapacity <= buf.MaxCapacity); int oldCapacity = buf.Length; if (oldCapacity == newCapacity) { return; } PoolChunk<T> oldChunk = buf.Chunk; long oldHandle = buf.Handle; T oldMemory = buf.Memory; int oldOffset = buf.Offset; int oldMaxLength = buf.MaxLength; int readerIndex = buf.ReaderIndex; int writerIndex = buf.WriterIndex; this.Allocate(this.Parent.ThreadCache<T>(), buf, newCapacity); if (newCapacity > oldCapacity) { this.MemoryCopy( oldMemory, oldOffset, buf.Memory, buf.Offset, oldCapacity); } else if (newCapacity < oldCapacity) { if (readerIndex < newCapacity) { if (writerIndex > newCapacity) { writerIndex = newCapacity; } this.MemoryCopy( oldMemory, oldOffset + readerIndex, buf.Memory, buf.Offset + readerIndex, writerIndex - readerIndex); } else { readerIndex = writerIndex = newCapacity; } } buf.SetIndex(readerIndex, writerIndex); if (freeOldMemory) { this.Free(oldChunk, oldHandle, oldMaxLength, buf.Cache); } } public int NumTinySubpages => this.tinySubpagePools.Length; public int NumSmallSubpages => this.smallSubpagePools.Length; public int NumChunkLists => this.chunkListMetrics.Count; public IReadOnlyList<IPoolSubpageMetric> TinySubpages => SubPageMetricList(this.tinySubpagePools); public IReadOnlyList<IPoolSubpageMetric> SmallSubpages => SubPageMetricList(this.smallSubpagePools); public IReadOnlyList<IPoolChunkListMetric> ChunkLists => this.chunkListMetrics; static List<IPoolSubpageMetric> SubPageMetricList(PoolSubpage<T>[] pages) { var metrics = new List<IPoolSubpageMetric>(); for (int i = 1; i < pages.Length; i++) { PoolSubpage<T> head = pages[i]; if (head.Next == head) { continue; } PoolSubpage<T> s = head.Next; for (;;) { metrics.Add(s); s = s.Next; if (s == head) { break; } } } return metrics; } public long NumAllocations => this.allocationsTiny + this.allocationsSmall + this.allocationsNormal + this.NumHugeAllocations; public long NumTinyAllocations => this.allocationsTiny; public long NumSmallAllocations => this.allocationsSmall; public long NumNormalAllocations => this.allocationsNormal; public long NumDeallocations => this.deallocationsTiny + this.deallocationsSmall + this.allocationsNormal + this.NumHugeDeallocations; public long NumTinyDeallocations => this.deallocationsTiny; public long NumSmallDeallocations => this.deallocationsSmall; public long NumNormalDeallocations => this.deallocationsNormal; public long NumHugeAllocations => Volatile.Read(ref this.allocationsHuge); public long NumHugeDeallocations => Volatile.Read(ref this.deallocationsHuge); public long NumActiveAllocations => Math.Max(this.NumAllocations - this.NumDeallocations, 0); public long NumActiveTinyAllocations => Math.Max(this.NumTinyAllocations - this.NumTinyDeallocations, 0); public long NumActiveSmallAllocations => Math.Max(this.NumSmallAllocations - this.NumSmallDeallocations, 0); public long NumActiveNormalAllocations { get { long val; lock (this) { val = this.NumNormalAllocations - this.NumNormalDeallocations; } return Math.Max(val, 0); } } public long NumActiveHugeAllocations => Math.Max(this.NumHugeAllocations - this.NumHugeDeallocations, 0); public long NumActiveBytes { get { long val = Volatile.Read(ref this.activeBytesHuge); lock (this) { for (int i = 0; i < this.chunkListMetrics.Count; i++) { foreach (IPoolChunkMetric m in this.chunkListMetrics[i]) { val += m.ChunkSize; } } } return Math.Max(0, val); } } protected abstract PoolChunk<T> NewChunk(int pageSize, int maxOrder, int pageShifts, int chunkSize); protected abstract PoolChunk<T> NewUnpooledChunk(int capacity); protected abstract PooledByteBuffer<T> NewByteBuf(int maxCapacity); protected abstract void MemoryCopy(T src, int srcOffset, T dst, int dstOffset, int length); protected abstract void DestroyChunk(PoolChunk<T> chunk); [MethodImpl(MethodImplOptions.Synchronized)] public override string ToString() { StringBuilder buf = new StringBuilder() .Append("Chunk(s) at 0~25%:") .Append(StringUtil.Newline) .Append(this.qInit) .Append(StringUtil.Newline) .Append("Chunk(s) at 0~50%:") .Append(StringUtil.Newline) .Append(this.q000) .Append(StringUtil.Newline) .Append("Chunk(s) at 25~75%:") .Append(StringUtil.Newline) .Append(this.q025) .Append(StringUtil.Newline) .Append("Chunk(s) at 50~100%:") .Append(StringUtil.Newline) .Append(this.q050) .Append(StringUtil.Newline) .Append("Chunk(s) at 75~100%:") .Append(StringUtil.Newline) .Append(this.q075) .Append(StringUtil.Newline) .Append("Chunk(s) at 100%:") .Append(StringUtil.Newline) .Append(this.q100) .Append(StringUtil.Newline) .Append("tiny subpages:"); for (int i = 1; i < this.tinySubpagePools.Length; i++) { PoolSubpage<T> head = this.tinySubpagePools[i]; if (head.Next == head) { continue; } buf.Append(StringUtil.Newline) .Append(i) .Append(": "); PoolSubpage<T> s = head.Next; for (;;) { buf.Append(s); s = s.Next; if (s == head) { break; } } } buf.Append(StringUtil.Newline) .Append("small subpages:"); for (int i = 1; i < this.smallSubpagePools.Length; i++) { PoolSubpage<T> head = this.smallSubpagePools[i]; if (head.Next == head) { continue; } buf.Append(StringUtil.Newline) .Append(i) .Append(": "); PoolSubpage<T> s = head.Next; for (;;) { buf.Append(s); s = s.Next; if (s == head) { break; } } } buf.Append(StringUtil.Newline); return buf.ToString(); } } sealed class HeapArena : PoolArena<byte[]> { public HeapArena(PooledByteBufferAllocator parent, int pageSize, int maxOrder, int pageShifts, int chunkSize) : base(parent, pageSize, maxOrder, pageShifts, chunkSize) { } protected override PoolChunk<byte[]> NewChunk(int pageSize, int maxOrder, int pageShifts, int chunkSize) => new PoolChunk<byte[]>(this, new byte[chunkSize], pageSize, maxOrder, pageShifts, chunkSize); protected override PoolChunk<byte[]> NewUnpooledChunk(int capacity) => new PoolChunk<byte[]>(this, new byte[capacity], capacity); protected override void DestroyChunk(PoolChunk<byte[]> chunk) { // Rely on GC. } protected override PooledByteBuffer<byte[]> NewByteBuf(int maxCapacity) => PooledHeapByteBuffer.NewInstance(maxCapacity); protected override void MemoryCopy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int length) { if (length == 0) { return; } Array.Copy(src, srcOffset, dst, dstOffset, length); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orleans; using Orleans.Concurrency; using Orleans.Providers; using Orleans.Providers.Streams.SimpleMessageStream; using Orleans.Runtime; using Orleans.Streams; using UnitTests.GrainInterfaces; using UnitTests.TestHelper; namespace UnitTests.Grains { [Serializable] [GenerateSerializer] public class StreamItem { [Id(0)] public string Data; [Id(1)] public Guid StreamId; public StreamItem(string data, Guid streamId) { Data = data; StreamId = streamId; } public override string ToString() { return String.Format("{0}", Data); } } [Serializable] [GenerateSerializer] public class ConsumerObserver : IAsyncObserver<StreamItem>, IConsumerObserver { [NonSerialized] private ILogger _logger; [NonSerialized] private StreamSubscriptionHandle<StreamItem> _subscription; [Id(0)] private int _itemsConsumed; [Id(1)] private Guid _streamId; [Id(2)] private string _streamNamespace; public Task<int> ItemsConsumed { get { return Task.FromResult(_itemsConsumed); } } private ConsumerObserver(ILogger logger) { _logger = logger; _itemsConsumed = 0; } public static ConsumerObserver NewObserver(ILogger logger) { if (null == logger) throw new ArgumentNullException("logger"); return new ConsumerObserver(logger); } public Task OnNextAsync(StreamItem item, StreamSequenceToken token = null) { if (!item.StreamId.Equals(_streamId)) { string excStr = String.Format("ConsumerObserver.OnNextAsync: received an item from the wrong stream." + " Got item {0} from stream = {1}, expecting stream = {2}, numConsumed={3}", item, item.StreamId, _streamId, _itemsConsumed); _logger.Error(0, excStr); throw new ArgumentException(excStr); } ++_itemsConsumed; string str = String.Format("ConsumerObserver.OnNextAsync: streamId={0}, item={1}, numConsumed={2}{3}", _streamId, item.Data, _itemsConsumed, token != null ? ", token = " + token : ""); if (ProducerObserver.DEBUG_STREAMING_GRAINS) { _logger.Info(str); } else { _logger.Debug(str); } return Task.CompletedTask; } public Task OnCompletedAsync() { _logger.Info("ConsumerObserver.OnCompletedAsync"); return Task.CompletedTask; } public Task OnErrorAsync(Exception ex) { _logger.Info("ConsumerObserver.OnErrorAsync: ex={0}", ex); return Task.CompletedTask; } public async Task BecomeConsumer(Guid streamId, IStreamProvider streamProvider, string streamNamespace) { _logger.Info("BecomeConsumer"); if (ProviderName != null) throw new InvalidOperationException("redundant call to BecomeConsumer"); _streamId = streamId; ProviderName = streamProvider.Name; _streamNamespace = string.IsNullOrWhiteSpace(streamNamespace) ? null : streamNamespace.Trim(); IAsyncStream<StreamItem> stream = streamProvider.GetStream<StreamItem>(streamId, streamNamespace); _subscription = await stream.SubscribeAsync(this); } public async Task RenewConsumer(ILogger logger, IStreamProvider streamProvider) { _logger = logger; _logger.Info("RenewConsumer"); IAsyncStream<StreamItem> stream = streamProvider.GetStream<StreamItem>(_streamId, _streamNamespace); _subscription = await stream.SubscribeAsync(this); } public async Task StopBeingConsumer(IStreamProvider streamProvider) { _logger.Info("StopBeingConsumer"); if (_subscription != null) { await _subscription.UnsubscribeAsync(); //_subscription.Dispose(); _subscription = null; } } public Task<int> ConsumerCount { get { return Task.FromResult(_subscription == null ? 0 : 1); } } [Id(3)] public string ProviderName { get; private set; } } [Serializable] [GenerateSerializer] public class ProducerObserver : IProducerObserver { [NonSerialized] private ILogger _logger; [NonSerialized] private IAsyncObserver<StreamItem> _observer; [NonSerialized] private Dictionary<IDisposable, TimerState> _timers; [Id(0)] private int _itemsProduced; [Id(1)] private int _expectedItemsProduced; [Id(2)] private Guid _streamId; [Id(3)] private string _streamNamespace; [Id(4)] private string _providerName; [Id(5)] private readonly InterlockedFlag _cleanedUpFlag; [NonSerialized] private bool _observerDisposedYet; [NonSerialized] private readonly IGrainFactory _grainFactory; public static bool DEBUG_STREAMING_GRAINS = true; private ProducerObserver(ILogger logger, IGrainFactory grainFactory) { _logger = logger; _observer = null; _timers = new Dictionary<IDisposable, TimerState>(); _itemsProduced = 0; _expectedItemsProduced = 0; _streamId = default(Guid); _providerName = null; _cleanedUpFlag = new InterlockedFlag(); _observerDisposedYet = false; _grainFactory = grainFactory; } public static ProducerObserver NewObserver(ILogger logger, IGrainFactory grainFactory) { if (null == logger) throw new ArgumentNullException("logger"); return new ProducerObserver(logger, grainFactory); } public void BecomeProducer(Guid streamId, IStreamProvider streamProvider, string streamNamespace) { _cleanedUpFlag.ThrowNotInitializedIfSet(); _logger.Info("BecomeProducer"); IAsyncStream<StreamItem> stream = streamProvider.GetStream<StreamItem>(streamId, streamNamespace); _observer = stream; var observerAsSMSProducer = _observer as SimpleMessageStreamProducer<StreamItem>; // only SimpleMessageStreamProducer implements IDisposable and a means to verify it was cleaned up. if (null == observerAsSMSProducer) { _logger.Info("ProducerObserver.BecomeProducer: producer requires no disposal; test short-circuited."); _observerDisposedYet = true; } else { _logger.Info("ProducerObserver.BecomeProducer: producer performs disposal during finalization."); observerAsSMSProducer.OnDisposeTestHook += () => _observerDisposedYet = true; } _streamId = streamId; _streamNamespace = string.IsNullOrWhiteSpace(streamNamespace) ? null : streamNamespace.Trim(); _providerName = streamProvider.Name; } public void RenewProducer(ILogger logger, IStreamProvider streamProvider) { _cleanedUpFlag.ThrowNotInitializedIfSet(); _logger = logger; _logger.Info("RenewProducer"); IAsyncStream<StreamItem> stream = streamProvider.GetStream<StreamItem>(_streamId, _streamNamespace); _observer = stream; var observerAsSMSProducer = _observer as SimpleMessageStreamProducer<StreamItem>; // only SimpleMessageStreamProducer implements IDisposable and a means to verify it was cleaned up. if (null == observerAsSMSProducer) { //_logger.Info("ProducerObserver.BecomeProducer: producer requires no disposal; test short-circuited."); _observerDisposedYet = true; } else { //_logger.Info("ProducerObserver.BecomeProducer: producer performs disposal during finalization."); observerAsSMSProducer.OnDisposeTestHook += () => _observerDisposedYet = true; } } private async Task<bool> ProduceItem(string data) { if (_cleanedUpFlag.IsSet) return false; StreamItem item = new StreamItem(data, _streamId); await _observer.OnNextAsync(item); _itemsProduced++; string str = String.Format("ProducerObserver.ProduceItem: streamId={0}, data={1}, numProduced so far={2}.", _streamId, data, _itemsProduced); if (DEBUG_STREAMING_GRAINS) { _logger.Info(str); } else { _logger.Debug(str); } return true; } public async Task ProduceSequentialSeries(int count) { _cleanedUpFlag.ThrowNotInitializedIfSet(); if (0 >= count) throw new ArgumentOutOfRangeException("count", "The count must be greater than zero."); _expectedItemsProduced += count; _logger.Info("ProducerObserver.ProduceSequentialSeries: streamId={0}, num items to produce={1}.", _streamId, count); for (var i = 1; i <= count; ++i) await ProduceItem(String.Format("sequential#{0}", i)); } public Task ProduceParallelSeries(int count) { _cleanedUpFlag.ThrowNotInitializedIfSet(); if (0 >= count) throw new ArgumentOutOfRangeException("count", "The count must be greater than zero."); _logger.Info("ProducerObserver.ProduceParallelSeries: streamId={0}, num items to produce={1}.", _streamId, count); _expectedItemsProduced += count; var tasks = new Task<bool>[count]; for (var i = 1; i <= count; ++i) { int capture = i; Func<Task<bool>> func = async () => { return await ProduceItem(String.Format("parallel#{0}", capture)); }; // Need to call on different threads to force parallel execution. tasks[capture - 1] = Task.Factory.StartNew(func).Unwrap(); } return Task.WhenAll(tasks); } public Task<int> ItemsProduced { get { _cleanedUpFlag.ThrowNotInitializedIfSet(); return Task.FromResult(_itemsProduced); } } public Task ProducePeriodicSeries(Func<Func<object, Task>, IDisposable> createTimerFunc, int count) { _cleanedUpFlag.ThrowNotInitializedIfSet(); _logger.Info("ProducerObserver.ProducePeriodicSeries: streamId={0}, num items to produce={1}.", _streamId, count); var timer = TimerState.NewTimer(createTimerFunc, ProduceItem, RemoveTimer, count); // we can't pass the TimerState object in as the argument-- it might be prematurely collected, so we root // it to this object via the _timers dictionary. _timers.Add(timer.Handle, timer); _expectedItemsProduced += count; timer.StartTimer(); return Task.CompletedTask; } private void RemoveTimer(IDisposable handle) { _logger.Info("ProducerObserver.RemoveTimer: streamId={0}.", _streamId); if (handle == null) throw new ArgumentNullException("handle"); if (!_timers.Remove(handle)) throw new InvalidOperationException("handle not found"); } public Task<Guid> StreamId { get { _cleanedUpFlag.ThrowNotInitializedIfSet(); return Task.FromResult(_streamId); } } public string ProviderName { get { _cleanedUpFlag.ThrowNotInitializedIfSet(); return _providerName; } } public Task AddNewConsumerGrain(Guid consumerGrainId) { var grain = _grainFactory.GetGrain<IStreaming_ConsumerGrain>(consumerGrainId, "UnitTests.Grains.Streaming_ConsumerGrain"); return grain.BecomeConsumer(_streamId, _providerName, _streamNamespace); } public Task<int> ExpectedItemsProduced { get { _cleanedUpFlag.ThrowNotInitializedIfSet(); return Task.FromResult(_expectedItemsProduced); } } public Task<int> ProducerCount { get { return Task.FromResult(_cleanedUpFlag.IsSet ? 0 : 1); } } public Task StopBeingProducer() { _logger.Info("StopBeingProducer"); if (!_cleanedUpFlag.TrySet()) return Task.CompletedTask; if (_timers != null) { foreach (var i in _timers) { try { i.Value.Dispose(); } catch (Exception exc) { _logger.Error(1, "StopBeingProducer: Timer Dispose() has thrown", exc); } } _timers = null; } _observer = null; // Disposing return Task.CompletedTask; } public async Task VerifyFinished() { _logger.Info("ProducerObserver.VerifyFinished: waiting for observer disposal; streamId={0}", _streamId); while (!_observerDisposedYet) { await Task.Delay(1000); GC.Collect(); GC.WaitForPendingFinalizers(); } _logger.Info("ProducerObserver.VerifyFinished: observer disposed; streamId={0}", _streamId); } private class TimerState : IDisposable { private bool _started; public IDisposable Handle { get; private set; } private int _counter; private readonly Func<string, Task<bool>> _produceItemFunc; private readonly Action<IDisposable> _onDisposeFunc; private readonly InterlockedFlag _disposedFlag; private TimerState(Func<string, Task<bool>> produceItemFunc, Action<IDisposable> onDisposeFunc, int count) { _produceItemFunc = produceItemFunc; _onDisposeFunc = onDisposeFunc; _counter = count; _disposedFlag = new InterlockedFlag(); } public static TimerState NewTimer(Func<Func<object, Task>, IDisposable> startTimerFunc, Func<string, Task<bool>> produceItemFunc, Action<IDisposable> onDisposeFunc, int count) { if (null == startTimerFunc) throw new ArgumentNullException("startTimerFunc"); if (null == produceItemFunc) throw new ArgumentNullException("produceItemFunc"); if (null == onDisposeFunc) throw new ArgumentNullException("onDisposeFunc"); if (0 >= count) throw new ArgumentOutOfRangeException("count", count, "argument must be > 0"); var newOb = new TimerState(produceItemFunc, onDisposeFunc, count); newOb.Handle = startTimerFunc(newOb.OnTickAsync); if (null == newOb.Handle) throw new InvalidOperationException("startTimerFunc must not return null"); return newOb; } public void StartTimer() { _disposedFlag.ThrowDisposedIfSet(GetType()); if (_started) throw new InvalidOperationException("timer already started"); _started = true; } private async Task OnTickAsync(object unused) { if (_started && !_disposedFlag.IsSet) { --_counter; bool shouldContinue = await _produceItemFunc(String.Format("periodic#{0}", _counter)); if (!shouldContinue || 0 == _counter) Dispose(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposedFlag.TrySet()) return; _onDisposeFunc(Handle); Handle.Dispose(); Handle = null; } } } [StorageProvider(ProviderName = "MemoryStore")] public class Streaming_ProducerGrain : Grain<Streaming_ProducerGrain_State>, IStreaming_ProducerGrain { private ILogger _logger; protected List<IProducerObserver> _producers; private InterlockedFlag _cleanedUpFlag; public override Task OnActivateAsync() { _logger = this.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger("Test.Streaming_ProducerGrain " + RuntimeIdentity + "/" + IdentityString + "/" + Data.ActivationId); _logger.Info("OnActivateAsync"); _producers = new List<IProducerObserver>(); _cleanedUpFlag = new InterlockedFlag(); return Task.CompletedTask; } public override Task OnDeactivateAsync() { _logger.Info("OnDeactivateAsync"); return Task.CompletedTask; } public virtual Task BecomeProducer(Guid streamId, string providerToUse, string streamNamespace) { _cleanedUpFlag.ThrowNotInitializedIfSet(); ProducerObserver producer = ProducerObserver.NewObserver(_logger, GrainFactory); producer.BecomeProducer(streamId, this.GetStreamProvider(providerToUse), streamNamespace); _producers.Add(producer); return Task.CompletedTask; } public virtual async Task ProduceSequentialSeries(int count) { _cleanedUpFlag.ThrowNotInitializedIfSet(); foreach (var producer in _producers) { await producer.ProduceSequentialSeries(count); } } public virtual async Task ProduceParallelSeries(int count) { _cleanedUpFlag.ThrowNotInitializedIfSet(); await Task.WhenAll(_producers.Select(p => p.ProduceParallelSeries(count)).ToArray()); } public virtual async Task ProducePeriodicSeries(int count) { _cleanedUpFlag.ThrowNotInitializedIfSet(); await Task.WhenAll(_producers.Select(p => p.ProducePeriodicSeries(timerCallback => { return RegisterTimer(timerCallback, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(10)); },count)).ToArray()); } public virtual async Task<int> GetExpectedItemsProduced() { var tasks = _producers.Select(p => p.ExpectedItemsProduced).ToArray(); int[] expectedItemsProduced = await Task.WhenAll(tasks); return expectedItemsProduced.Sum(); } public virtual async Task<int> GetItemsProduced() { var tasks = _producers.Select(p => p.ItemsProduced).ToArray(); int[] itemsProduced = await Task.WhenAll(tasks); return itemsProduced.Sum(); } public virtual async Task AddNewConsumerGrain(Guid consumerGrainId) { _cleanedUpFlag.ThrowNotInitializedIfSet(); await Task.WhenAll(_producers.Select( target => target.AddNewConsumerGrain(consumerGrainId)).ToArray()); } public virtual async Task<int> GetProducerCount() { _cleanedUpFlag.ThrowNotInitializedIfSet(); var tasks = _producers.Select(p => p.ProducerCount).ToArray(); int[] producerCount = await Task.WhenAll(tasks); return producerCount.Sum(); } public virtual async Task StopBeingProducer() { if (!_cleanedUpFlag.TrySet()) return; var tasks = _producers.Select(p => p.StopBeingProducer()).ToArray(); await Task.WhenAll(tasks); } public virtual async Task VerifyFinished() { var tasks = _producers.Select(p => p.VerifyFinished()).ToArray(); await Task.WhenAll(tasks); _producers.Clear(); } public virtual Task DeactivateProducerOnIdle() { _logger.Info("DeactivateProducerOnIdle"); DeactivateOnIdle(); return Task.CompletedTask; } } [StorageProvider(ProviderName = "MemoryStore")] public class PersistentStreaming_ProducerGrain : Streaming_ProducerGrain, IStreaming_ProducerGrain { private ILogger _logger; public override async Task OnActivateAsync() { await base.OnActivateAsync(); _logger = this.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger("Test.PersistentStreaming_ProducerGrain " + RuntimeIdentity + "/" + IdentityString + "/" + Data.ActivationId); _logger.Info("OnActivateAsync"); if (State.Producers == null) { State.Producers = new List<IProducerObserver>(); _producers = State.Producers; } else { foreach (var producer in State.Producers) { producer.RenewProducer(_logger, this.GetStreamProvider(producer.ProviderName)); _producers.Add(producer); } } } public override Task OnDeactivateAsync() { _logger.Info("OnDeactivateAsync"); return base.OnDeactivateAsync(); } public override async Task BecomeProducer(Guid streamId, string providerToUse, string streamNamespace) { await base.BecomeProducer(streamId, providerToUse, streamNamespace); State.Producers = _producers; await WriteStateAsync(); } public override async Task ProduceSequentialSeries(int count) { await base.ProduceParallelSeries(count); State.Producers = _producers; await WriteStateAsync(); } public override async Task ProduceParallelSeries(int count) { await base.ProduceParallelSeries(count); State.Producers = _producers; await WriteStateAsync(); } public override async Task StopBeingProducer() { await base.StopBeingProducer(); State.Producers = _producers; await WriteStateAsync(); } public override async Task VerifyFinished() { await base.VerifyFinished(); await ClearStateAsync(); } } [StorageProvider(ProviderName = "MemoryStore")] public class Streaming_ConsumerGrain : Grain<Streaming_ConsumerGrain_State>, IStreaming_ConsumerGrain { private ILogger _logger; protected List<IConsumerObserver> _observers; private string _providerToUse; public override Task OnActivateAsync() { _logger = this.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger("Test.Streaming_ConsumerGrain " + RuntimeIdentity + "/" + IdentityString + "/" + Data.ActivationId); _logger.Info("OnActivateAsync"); _observers = new List<IConsumerObserver>(); return Task.CompletedTask; } public override Task OnDeactivateAsync() { _logger.Info("OnDeactivateAsync"); return Task.CompletedTask; } public async virtual Task BecomeConsumer(Guid streamId, string providerToUse, string streamNamespace) { _providerToUse = providerToUse; ConsumerObserver consumerObserver = ConsumerObserver.NewObserver(_logger); await consumerObserver.BecomeConsumer(streamId, this.GetStreamProvider(providerToUse), streamNamespace); _observers.Add(consumerObserver); } public virtual async Task<int> GetItemsConsumed() { var tasks = _observers.Select(p => p.ItemsConsumed).ToArray(); int[] itemsConsumed = await Task.WhenAll(tasks); return itemsConsumed.Sum(); } public virtual async Task<int> GetConsumerCount() { var tasks = _observers.Select(p => p.ConsumerCount).ToArray(); int[] consumerCount = await Task.WhenAll(tasks); return consumerCount.Sum(); } public virtual async Task StopBeingConsumer() { var tasks = _observers.Select(obs => obs.StopBeingConsumer(this.GetStreamProvider(_providerToUse))).ToArray(); await Task.WhenAll(tasks); _observers.Clear(); } public virtual Task DeactivateConsumerOnIdle() { _logger.Info("DeactivateConsumerOnIdle"); Task.Delay(TimeSpan.FromSeconds(2)).ContinueWith(task => { _logger.Info("DeactivateConsumerOnIdle ContinueWith fired."); }).Ignore(); // .WithTimeout(TimeSpan.FromSeconds(2)); DeactivateOnIdle(); return Task.CompletedTask; } } [StorageProvider(ProviderName = "MemoryStore")] public class PersistentStreaming_ConsumerGrain : Streaming_ConsumerGrain, IPersistentStreaming_ConsumerGrain { private ILogger _logger; public override async Task OnActivateAsync() { await base.OnActivateAsync(); _logger = this.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger("Test.PersistentStreaming_ConsumerGrain " + RuntimeIdentity + "/" + IdentityString + "/" + Data.ActivationId); _logger.Info("OnActivateAsync"); if (State.Consumers == null) { State.Consumers = new List<IConsumerObserver>(); _observers = State.Consumers; } else { foreach (var consumer in State.Consumers) { await consumer.RenewConsumer(_logger, this.GetStreamProvider(consumer.ProviderName)); _observers.Add(consumer); } } } public override async Task OnDeactivateAsync() { _logger.Info("OnDeactivateAsync"); await base.OnDeactivateAsync(); } public override async Task BecomeConsumer(Guid streamId, string providerToUse, string streamNamespace) { await base.BecomeConsumer(streamId, providerToUse, streamNamespace); State.Consumers = _observers; await WriteStateAsync(); } public override async Task StopBeingConsumer() { await base.StopBeingConsumer(); State.Consumers = _observers; await WriteStateAsync(); } } [Reentrant] public class Streaming_Reentrant_ProducerConsumerGrain : Streaming_ProducerConsumerGrain, IStreaming_Reentrant_ProducerConsumerGrain { private ILogger _logger; public override async Task OnActivateAsync() { _logger = this.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger("Test.Streaming_Reentrant_ProducerConsumerGrain " + RuntimeIdentity + "/" + IdentityString + "/" + Data.ActivationId) ; _logger.Info("OnActivateAsync"); await base.OnActivateAsync(); } } public class Streaming_ProducerConsumerGrain : Grain, IStreaming_ProducerConsumerGrain { private ILogger _logger; private ProducerObserver _producer; private ConsumerObserver _consumer; private string _providerToUseForConsumer; public override Task OnActivateAsync() { _logger = this.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger("Test.Streaming_ProducerConsumerGrain " + RuntimeIdentity + "/" + IdentityString + "/" + Data.ActivationId); _logger.Info("OnActivateAsync"); return Task.CompletedTask; } public override Task OnDeactivateAsync() { _logger.Info("OnDeactivateAsync"); return Task.CompletedTask; } public Task BecomeProducer(Guid streamId, string providerToUse, string streamNamespace) { _producer = ProducerObserver.NewObserver(_logger, GrainFactory); _producer.BecomeProducer(streamId, this.GetStreamProvider(providerToUse), streamNamespace); return Task.CompletedTask; } public Task ProduceSequentialSeries(int count) { return _producer.ProduceSequentialSeries(count); } public Task ProduceParallelSeries(int count) { return _producer.ProduceParallelSeries(count); } public Task ProducePeriodicSeries(int count) { return _producer.ProducePeriodicSeries(timerCallback => { return RegisterTimer(timerCallback, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(10)); }, count); } public Task<int> GetItemsProduced() { return _producer.ItemsProduced; } public Task AddNewConsumerGrain(Guid consumerGrainId) { return _producer.AddNewConsumerGrain(consumerGrainId); } public async Task BecomeConsumer(Guid streamId, string providerToUse, string streamNamespace) { _providerToUseForConsumer = providerToUse; _consumer = ConsumerObserver.NewObserver(this._logger); await _consumer.BecomeConsumer(streamId, this.GetStreamProvider(providerToUse), streamNamespace); } public async Task<int> GetItemsConsumed() { return await _consumer.ItemsConsumed; } public async Task<int> GetExpectedItemsProduced() { return await _producer.ExpectedItemsProduced; } public async Task<int> GetConsumerCount() { return await _consumer.ConsumerCount; } public async Task<int> GetProducerCount() { return await _producer.ProducerCount; } public async Task StopBeingConsumer() { await _consumer.StopBeingConsumer(this.GetStreamProvider(_providerToUseForConsumer)); _consumer = null; } public async Task StopBeingProducer() { await _producer.StopBeingProducer(); } public async Task VerifyFinished() { await _producer.VerifyFinished(); _producer = null; } public Task DeactivateConsumerOnIdle() { DeactivateOnIdle(); return Task.CompletedTask; } public Task DeactivateProducerOnIdle() { _logger.Info("DeactivateProducerOnIdle"); DeactivateOnIdle(); return Task.CompletedTask; } } public abstract class Streaming_ImplicitlySubscribedConsumerGrainBase : Grain { private ILogger _logger; private Dictionary<string, IConsumerObserver> _observers; public override async Task OnActivateAsync() { _logger = this.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger("Test.Streaming_ImplicitConsumerGrain1 " + RuntimeIdentity + "/" + IdentityString + "/" + Data.ActivationId); _logger.Info("{0}.OnActivateAsync", GetType().FullName); _observers = new Dictionary<string, IConsumerObserver>(); // discuss: Note that we need to know the provider that will be used in advance. I think it would be beneficial if we specified the provider as an argument to ImplicitConsumerActivationAttribute. var activeStreamProviders = Runtime.ServiceProvider .GetService<IKeyedServiceCollection<string,IStreamProvider>>() .GetServices(Runtime.ServiceProvider) .Select(service => service.Key).ToList(); await Task.WhenAll(activeStreamProviders.Select(stream => BecomeConsumer(this.GetPrimaryKey(), stream, "TestNamespace1"))); } public override Task OnDeactivateAsync() { _logger.Info("OnDeactivateAsync"); return Task.CompletedTask; } public async Task BecomeConsumer(Guid streamGuid, string providerToUse, string streamNamespace) { if (_observers.ContainsKey(providerToUse)) { throw new InvalidOperationException(string.Format("consumer already established for provider {0}.", providerToUse)); } if (string.IsNullOrWhiteSpace(streamNamespace)) { throw new ArgumentException("namespace is required (must not be null or whitespace)", "streamNamespace"); } ConsumerObserver consumerObserver = ConsumerObserver.NewObserver(_logger); await consumerObserver.BecomeConsumer(streamGuid, this.GetStreamProvider(providerToUse), streamNamespace); _observers[providerToUse] = consumerObserver; } public virtual async Task<int> GetItemsConsumed() { int result = 0; foreach (var o in _observers.Values) { result += await o.ItemsConsumed; } return result; } public virtual Task<int> GetConsumerCount() { // it's currently impossible to detect how many implicit consumers are being used, // so we must resort to hard-wiring this grain to only use one provider's consumer at a time. // this problem will continue until we require the provider's name to be apart of the implicit subscriber attribute identity. return Task.FromResult(1); /* int result = 0; foreach (var o in _observers.Values) { result += await o.ConsumerCount; } return result; */ } public async Task StopBeingConsumer() { await Task.WhenAll(_observers.Select(i => i.Value.StopBeingConsumer(this.GetStreamProvider(i.Key)))); _observers = null; } public Task DeactivateConsumerOnIdle() { _logger.Info("DeactivateConsumerOnIdle"); Task.Delay(TimeSpan.FromSeconds(2)).ContinueWith(task => { _logger.Info("DeactivateConsumerOnIdle ContinueWith fired."); }).Ignore(); // .WithTimeout(TimeSpan.FromSeconds(2)); DeactivateOnIdle(); return Task.CompletedTask; } } [ImplicitStreamSubscription("TestNamespace1")] public class Streaming_ImplicitlySubscribedConsumerGrain : Streaming_ImplicitlySubscribedConsumerGrainBase, IStreaming_ImplicitlySubscribedConsumerGrain {} }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration using VB = Microsoft.VisualBasic; namespace _4PosBackOffice.NET { internal partial class frmUpdateDayEnd : System.Windows.Forms.Form { short gCNT; short gTotal; private void loadLanguage() { //Label1 = No Code [Updating Report Data...] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1.Caption = rsLang("LanguageLayoutLnk_Description"): Label1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmUpdateDayEnd.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } private bool buildPath1(ref string lPath) { bool functionReturnValue = false; ADOX.Catalog cat = default(ADOX.Catalog); ADOX.Table tbl = default(ADOX.Table); ADODB.Recordset rs = default(ADODB.Recordset); ADODB.Connection cn = new ADODB.Connection(); string lFile = null; string holdfile = null; string[] lArray = null; short x = 0; Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); string lDir = null; cat = new ADOX.Catalog(); tbl = new ADOX.Table(); // ERROR: Not supported in C#: OnErrorStatement Cursor = System.Windows.Forms.Cursors.WaitCursor; if (modReport.cnnDBreport == null) { } else { cat.let_ActiveConnection(modReport.cnnDBreport); foreach ( tbl in cat.Tables) { if (tbl.Type == "LINK") { System.Windows.Forms.Application.DoEvents(); tbl.Properties("Jet OLEDB:Link Datasource").Value = modRecordSet.serverPath + "pricing.mdb"; //Replace(LCase(tbl.Properties("Jet OLEDB:Link Datasource")), LCase("C:\4posServer\"), serverPath) } } cat = null; cn.Close(); cn = null; cat = new ADOX.Catalog(); } System.Windows.Forms.Application.DoEvents(); Cursor = System.Windows.Forms.Cursors.Default; functionReturnValue = true; return functionReturnValue; buildPath_Error: Cursor = System.Windows.Forms.Cursors.Default; Interaction.MsgBox(Err().Description); functionReturnValue = false; return functionReturnValue; } private void linkTables(ref string source) { ADOX.Catalog cat = default(ADOX.Catalog); ADOX.Table tbl = default(ADOX.Table); Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); if (fso.FileExists(modRecordSet.serverPath + source + ".mdb")) { } else { return; } cat = new ADOX.Catalog(); short x = 0; // Open the catalog. cat.let_ActiveConnection(modReport.cnnDBreport); for (x = cat.Tables.Count - 1; x >= 0; x += -1) { switch (Strings.LCase(cat.Tables(x).name)) { case "acustomertransaction": case "adayendstockitemlnk": case "adeclaration": case "asale": case "asaleitem": case "asuppliertransaction": cat.Tables.delete(cat.Tables(x).name); break; } } tbl = new ADOX.Table(); tbl.name = "aCustomerTransaction"; tbl.ParentCatalog = cat; tbl.Properties("Jet OLEDB:Link Datasource").Value = modRecordSet.serverPath + source + ".mdb"; tbl.Properties("Jet OLEDB:Remote Table Name").Value = "CustomerTransaction"; tbl.Properties("Jet OLEDB:Create Link").Value = true; cat.Tables.Append(tbl); tbl = new ADOX.Table(); tbl.name = "aDayEndStockItemLnk"; tbl.ParentCatalog = cat; tbl.Properties("Jet OLEDB:Link Datasource").Value = modRecordSet.serverPath + source + ".mdb"; tbl.Properties("Jet OLEDB:Remote Table Name").Value = "DayEndStockItemLnk"; tbl.Properties("Jet OLEDB:Create Link").Value = true; cat.Tables.Append(tbl); tbl = new ADOX.Table(); tbl.name = "aDeclaration"; tbl.ParentCatalog = cat; tbl.Properties("Jet OLEDB:Link Datasource").Value = modRecordSet.serverPath + source + ".mdb"; tbl.Properties("Jet OLEDB:Remote Table Name").Value = "Declaration"; tbl.Properties("Jet OLEDB:Create Link").Value = true; cat.Tables.Append(tbl); tbl = new ADOX.Table(); tbl.name = "aSale"; tbl.ParentCatalog = cat; tbl.Properties("Jet OLEDB:Link Datasource").Value = modRecordSet.serverPath + source + ".mdb"; tbl.Properties("Jet OLEDB:Remote Table Name").Value = "Sale"; tbl.Properties("Jet OLEDB:Create Link").Value = true; cat.Tables.Append(tbl); tbl = new ADOX.Table(); tbl.name = "aSaleItem"; tbl.ParentCatalog = cat; tbl.Properties("Jet OLEDB:Link Datasource").Value = modRecordSet.serverPath + source + ".mdb"; tbl.Properties("Jet OLEDB:Remote Table Name").Value = "SaleItem"; tbl.Properties("Jet OLEDB:Create Link").Value = true; cat.Tables.Append(tbl); tbl = new ADOX.Table(); tbl.name = "aSupplierTransaction"; tbl.ParentCatalog = cat; tbl.Properties("Jet OLEDB:Link Datasource").Value = modRecordSet.serverPath + source + ".mdb"; tbl.Properties("Jet OLEDB:Remote Table Name").Value = "SupplierTransaction"; tbl.Properties("Jet OLEDB:Create Link").Value = true; cat.Tables.Append(tbl); cat.Tables.Refresh(); cat = null; } private void linkFirstTable(ref string source) { ADOX.Catalog cat = default(ADOX.Catalog); ADOX.Table tbl = default(ADOX.Table); Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); // ERROR: Not supported in C#: OnErrorStatement if (fso.FileExists(modRecordSet.serverPath + source + ".mdb")) { } else { return; } cat = new ADOX.Catalog(); short x = 0; // Open the catalog. cat.let_ActiveConnection(modReport.cnnDBreport); for (x = cat.Tables.Count - 1; x >= 0; x += -1) { switch (Strings.LCase(cat.Tables(x).name)) { case "adayendstockitemlnk": cat.Tables.delete(cat.Tables(x).name); break; } } tbl = new ADOX.Table(); tbl.name = "aDayEndStockItemLnk"; tbl.ParentCatalog = cat; tbl.Properties("Jet OLEDB:Link Datasource").Value = modRecordSet.serverPath + source + ".mdb"; tbl.Properties("Jet OLEDB:Remote Table Name").Value = "DayEndStockItemLnk"; tbl.Properties("Jet OLEDB:Create Link").Value = true; cat.Tables.Append(tbl); cat.Tables.Refresh(); cat = null; return; withPass: openConnection_linkFirstTable: //cat.ActiveConnection("Jet OLEDB:Database Password") = "lqd" //Resume Next //Exit Sub //If Err.Description = "[Microsoft][ODBC Microsoft Access Driver] Not a valid password." Then // GoTo withPass //ElseIf Err.Description = "Not a valid password." Then // GoTo withPass //Else Interaction.MsgBox(Err().Number + " - " + Err().Description); //End If } private void moveItem() { gCNT = gCNT + 1; picInner.Width = sizeConvertors.twipsToPixels(Convert.ToInt16(sizeConvertors.pixelToTwips(picOuter.Width, true) / gTotal * gCNT) + 100, true); System.Windows.Forms.Application.DoEvents(); } private void beginUpdate() { bool gModeReport = false; // ERROR: Not supported in C#: OnErrorStatement picInner.Width = 0; gCNT = 0; System.Windows.Forms.Application.DoEvents(); short x = 0; string sql = null; ADODB.Recordset rs = default(ADODB.Recordset); ADODB.Recordset rsChk = default(ADODB.Recordset); Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); bool lMode = false; gModeReport = false; if (Strings.Left(modRecordSet.serverPath, 3) == "c:\\") { } else { buildPath1(ref modRecordSet.serverPath); } Label1.Text = "Loading Report ..."; //Dim ccndbReport As Connection string[] lTable = null; short y = 0; lTable = Strings.Split("aChannel,aCompany,aConsignment,aCustomer,aDayEnd,aDayEndDepositItemLnk,aDeposit,aftConstruct,aftData,aftDataItem,aftSet,aGRV,aGRVDeposit,aGRVitem,aPackSize,aPayout,aPerson,aPOS,aPricingGroup,aPurchaseOrder,aRecipe,aRecipeStockitemLnk,aSaleItemReciept,aShrink,aStockBreakTransaction,aStockGroup,aStockItem,aStockTakeDetail,Supplier,Vat", ","); System.Windows.Forms.Application.DoEvents(); gTotal = 9 + 1 * 9; //ccndbReport.Close //Set ccndbReport = openConnectionInstance("templatereport.mdb") for (y = 0; y <= Information.UBound(lTable); y++) { moveItem(); System.Windows.Forms.Application.DoEvents(); modReport.cnnDBreport.Execute("DELETE * FROM " + lTable[y] + ";"); modReport.cnnDBreport.Execute("INSERT INTO " + lTable[y] + " SELECT * FROM " + lTable[y] + "1;"); } Label1.Text = "Updating Report Data ..."; picInner.Width = 0; gCNT = 0; System.Windows.Forms.Application.DoEvents(); modReport.cnnDBreport.Execute("DELETE * FROM DayEnd"); modReport.cnnDBreport.Execute("INSERT INTO dayend ( DayEndID, DayEnd_MonthEndID, DayEnd_Date ) SELECT aDayEnd.DayEndID, aDayEnd.DayEnd_MonthEndID, aDayEnd.DayEnd_Date From aDayEnd, Report WHERE (((aDayEnd.DayEndID)>=[Report]![Report_DayEndStartID] And (aDayEnd.DayEndID)<=[Report]![Report_DayEndEndID]));"); modReport.cnnDBreport.Execute("DELETE DayEndStockItemLnkFirst.* FROM DayEndStockItemLnkFirst;"); //Error in aCompany showing old wrong data if month end is done //Set rs = getRSreport("SELECT aDayEnd.*, aCompany.Company_DayEndID, aCompany.Company_MonthEndID From aDayEnd, Report, aCompany WHERE (((aDayEnd.DayEndID)=[Report]![Report_DayEndStartID]-1));") rs = modReport.getRSreport(ref "SELECT aDayEnd.*, aCompany1.Company_DayEndID, aCompany1.Company_MonthEndID From aDayEnd, Report, aCompany1 WHERE (((aDayEnd.DayEndID)=[Report]![Report_DayEndStartID]-1));"); if (rs.RecordCount) { if (rs.Fields("DayEnd_MonthEndID").Value == rs.Fields("Company_MonthEndID").Value) { linkFirstTable(ref "pricing"); } else { linkFirstTable(ref "month" + rs.Fields("DayEnd_MonthEndID").Value); } modReport.cnnDBreport.Execute("INSERT INTO DayEndStockItemLnkFirst SELECT aDayEndStockItemLnk.* FROM Report, aDayEndStockItemLnk INNER JOIN aDayEnd ON aDayEndStockItemLnk.DayEndStockItemLnk_DayEndID = aDayEnd.DayEndID WHERE (((aDayEnd.DayEndID)=[Report]![Report_DayEndStartID]-1));"); } rs.Close(); //Error in aCompany showing old wrong data if month end is done //Set rs = getRSreport("SELECT DISTINCT DayEnd.DayEnd_MonthEndID, aCompany.Company_MonthEndID FROM DayEnd, aCompany;") rs = modReport.getRSreport(ref "SELECT DISTINCT DayEnd.DayEnd_MonthEndID, aCompany1.Company_MonthEndID FROM DayEnd, aCompany1;"); gTotal = 9 + rs.RecordCount * 9; moveItem(); modReport.cnnDBreport.Execute("DELETE Payout.* FROM Payout;"); modReport.cnnDBreport.Execute("INSERT INTO Payout SELECT aPayout.* From Report, aPayout WHERE (((aPayout.Payout_DayEndID)>=[Report]![Report_DayEndStartID] And (aPayout.Payout_DayEndID)<=[Report]![Report_DayEndEndID]));"); moveItem(); modReport.cnnDBreport.Execute("DELETE aStockTakeDetail.* FROM aStockTakeDetail;"); modReport.cnnDBreport.Execute("INSERT INTO aStockTakeDetail SELECT aStockTakeDetail1.* From Report, aStockTakeDetail1 WHERE (((aStockTakeDetail1.StockTake_DayEndID)>=[Report]![Report_DayEndStartID] And (aStockTakeDetail1.StockTake_DayEndID)<=[Report]![Report_DayEndEndID]));"); moveItem(); modReport.cnnDBreport.Execute("DELETE * FROM DayEndStockItemLnk"); moveItem(); modReport.cnnDBreport.Execute("DELETE * FROM DayEndDepositItemLnk"); moveItem(); modReport.cnnDBreport.Execute("DELETE SaleItem.* FROM SaleItem;"); moveItem(); //consignment setting in report modReport.cnnDBreport.Execute("DELETE aConsignment.* FROM aConsignment;"); moveItem(); modReport.cnnDBreport.Execute("DELETE Sale.* FROM Sale;"); moveItem(); modReport.cnnDBreport.Execute("DELETE CustomerTransaction.* FROM CustomerTransaction;"); moveItem(); modReport.cnnDBreport.Execute("DELETE Declaration.* FROM Declaration;"); moveItem(); modReport.cnnDBreport.Execute("DELETE SupplierTransaction.* FROM SupplierTransaction;"); moveItem(); while (!(rs.EOF)) { if (rs.Fields("DayEnd_MonthEndID").Value == rs.Fields("Company_MonthEndID").Value) { linkTables(ref "pricing"); } else { linkTables(ref "month" + rs.Fields("DayEnd_MonthEndID").Value); } moveItem(); modReport.cnnDBreport.Execute("INSERT INTO DayEndStockItemLnk SELECT aDayEndStockItemLnk.* FROM aDayEndStockItemLnk INNER JOIN DayEnd ON aDayEndStockItemLnk.DayEndStockItemLnk_DayEndID = DayEnd.DayEndID;"); moveItem(); // ERROR: Not supported in C#: OnErrorStatement modReport.cnnDBreport.Execute("INSERT INTO DayEndDepositItemLnk SELECT aDayEndDepositItemLnk.* FROM aDayEndDepositItemLnk INNER JOIN DayEnd ON aDayEndDepositItemLnk.DayEndDepositItemLnk_DayEndID = DayEnd.DayEndID;"); moveItem(); if (My.MyProject.Forms.frmMenu.gSuper == true) { modReport.cnnDBreport.Execute("INSERT INTO sale SELECT aSale.* FROM [SELECT aSale.* FROM aSale LEFT JOIN Sale ON aSale.SaleID = Sale.SaleID WHERE (((Sale.SaleID) Is Null))]. AS aSale, Report WHERE (((aSale.Sale_DayEndID)>=[Report]![Report_DayEndStartID] And (aSale.Sale_DayEndID)<=[Report]![Report_DayEndEndID]));"); } else { if (rsChk.State) rsChk.Close(); rsChk = modReport.getRSreport(ref "SELECT TOP 1 * FROM aSale;"); if (rsChk.Fields.Count < 30) { modReport.cnnDBreport.Execute("INSERT INTO sale SELECT aSale.* FROM [SELECT aSale.* FROM aSale LEFT JOIN Sale ON aSale.SaleID = Sale.SaleID WHERE (((Sale.SaleID) Is Null))]. AS aSale, Report WHERE (((aSale.Sale_DayEndID)>=[Report]![Report_DayEndStartID] And (aSale.Sale_DayEndID)<=[Report]![Report_DayEndEndID]));"); } else { modReport.cnnDBreport.Execute("INSERT INTO sale SELECT aSale.* FROM [SELECT aSale.* FROM aSale LEFT JOIN Sale ON aSale.SaleID = Sale.SaleID WHERE (((Sale.SaleID) Is Null))]. AS aSale, Report WHERE ((((aSale.Sale_SaleChk)=False) And (aSale.Sale_DayEndID)>=[Report]![Report_DayEndStartID] And (aSale.Sale_DayEndID)<=[Report]![Report_DayEndEndID]));"); } rsChk.Close(); } moveItem(); modReport.cnnDBreport.Execute("INSERT INTO SaleItem SELECT aSaleItem.* FROM (aSaleItem INNER JOIN Sale ON aSaleItem.SaleItem_SaleID = Sale.SaleID) LEFT JOIN SaleItem ON aSaleItem.SaleItemID = SaleItem.SaleItemID WHERE (((SaleItem.SaleItemID) Is Null));"); moveItem(); //consignment setting in report modReport.cnnDBreport.Execute("INSERT INTO aConsignment SELECT aConsignment1.* FROM aConsignment1;"); moveItem(); if (rs.Fields("DayEnd_MonthEndID").Value == rs.Fields("Company_MonthEndID").Value) { modReport.cnnDBreport.Execute("INSERT INTO CustomerTransaction SELECT aCustomerTransaction.* From Report, aCustomerTransaction WHERE (((aCustomerTransaction.CustomerTransaction_MonthEndID)=" + rs.Fields("DayEnd_MonthEndID").Value + ") AND ((aCustomerTransaction.CustomerTransaction_DayEndID)>=[Report]![Report_DayEndStartID] And (aCustomerTransaction.CustomerTransaction_DayEndID)<=[Report]![Report_DayEndEndID]));"); } else { modReport.cnnDBreport.Execute("INSERT INTO CustomerTransaction SELECT aCustomerTransaction.* From Report, aCustomerTransaction WHERE (((aCustomerTransaction.CustomerTransaction_MonthEndID)=" + rs.Fields("DayEnd_MonthEndID").Value + ") AND ((aCustomerTransaction.CustomerTransaction_DayEndID)>=[Report]![Report_DayEndStartID] And (aCustomerTransaction.CustomerTransaction_DayEndID)<=[Report]![Report_DayEndEndID]));"); } moveItem(); sql = "INSERT INTO SupplierTransaction ( SupplierTransactionID, SupplierTransaction_SupplierID, SupplierTransaction_PersonID, SupplierTransaction_TransactionTypeID, SupplierTransaction_MonthEndID, SupplierTransaction_MonthEndIDFor, SupplierTransaction_DayEndID, SupplierTransaction_ReferenceID, SupplierTransaction_Date, SupplierTransaction_Description, SupplierTransaction_Amount, SupplierTransaction_Reference )"; sql = sql + "SELECT aSupplierTransaction.SupplierTransactionID, aSupplierTransaction.SupplierTransaction_SupplierID, aSupplierTransaction.SupplierTransaction_PersonID, aSupplierTransaction.SupplierTransaction_TransactionTypeID, aSupplierTransaction.SupplierTransaction_MonthEndID, aSupplierTransaction.SupplierTransaction_MonthEndIDFor, aSupplierTransaction.SupplierTransaction_DayEndID, aSupplierTransaction.SupplierTransaction_ReferenceID, aSupplierTransaction.SupplierTransaction_Date, aSupplierTransaction.SupplierTransaction_Description, aSupplierTransaction.SupplierTransaction_Amount, aSupplierTransaction.SupplierTransaction_Reference FROM aSupplierTransaction INNER JOIN DayEnd ON aSupplierTransaction.SupplierTransaction_DayEndID = DayEnd.DayEndID;"; sql = "INSERT INTO SupplierTransaction ( SupplierTransactionID, SupplierTransaction_SupplierID, SupplierTransaction_PersonID, SupplierTransaction_TransactionTypeID, SupplierTransaction_MonthEndID, SupplierTransaction_MonthEndIDFor, SupplierTransaction_DayEndID, SupplierTransaction_ReferenceID, SupplierTransaction_Date, SupplierTransaction_Description, SupplierTransaction_Amount, SupplierTransaction_Reference ) "; sql = sql + "SELECT [SupplierTransaction_MonthEndID] & [SupplierTransactionID] AS Expr1, aSupplierTransaction.SupplierTransaction_SupplierID, aSupplierTransaction.SupplierTransaction_PersonID, aSupplierTransaction.SupplierTransaction_TransactionTypeID, aSupplierTransaction.SupplierTransaction_MonthEndID, aSupplierTransaction.SupplierTransaction_MonthEndIDFor, aSupplierTransaction.SupplierTransaction_DayEndID, aSupplierTransaction.SupplierTransaction_ReferenceID, aSupplierTransaction.SupplierTransaction_Date, aSupplierTransaction.SupplierTransaction_Description, aSupplierTransaction.SupplierTransaction_Amount, aSupplierTransaction.SupplierTransaction_Reference FROM aSupplierTransaction INNER JOIN DayEnd ON aSupplierTransaction.SupplierTransaction_DayEndID = DayEnd.DayEndID;"; modReport.cnnDBreport.Execute(sql); moveItem(); modReport.cnnDBreport.Execute("INSERT INTO Declaration SELECT aDeclaration.* From Report, aDeclaration WHERE (((aDeclaration.Declaration_DayEndID)>=[Report]![Report_DayEndStartID] And (aDeclaration.Declaration_DayEndID)<=[Report]![Report_DayEndEndID]));"); moveItem(); modReport.cnnDBreport.Execute("UPDATE aCompany INNER JOIN (DayEndStockItemLnk INNER JOIN aStockItem ON DayEndStockItemLnk.DayEndStockItemLnk_StockItemID = aStockItem.StockItemID) ON aCompany.Company_DayEndID = DayEndStockItemLnk.DayEndStockItemLnk_DayEndID SET DayEndStockItemLnk.DayEndStockItemLnk_ListCost = [aStockItem]![StockItem_ListCost]/[aStockItem]![StockItem_Quantity], DayEndStockItemLnk.DayEndStockItemLnk_ActualCost = [aStockItem]![StockItem_ActualCost]/[aStockItem]![StockItem_Quantity];"); moveItem(); rs.moveNext(); } moveItem(); modReport.cnnDBreport.Execute("UPDATE Report SET Report.Report_Type = " + lMode + ";"); rs = modReport.getRSreport(ref "SELECT DayEnd.DayEndID FROM aCompany INNER JOIN DayEnd ON aCompany.Company_DayEndID = DayEnd.DayEndID;"); if (rs.RecordCount) { modReport.cnnDBreport.Execute("UPDATE Report SET Report.Report_Heading = [Report_Heading] & '(*)';"); modReport.cnnDBreport.Execute("UPDATE aCompany INNER JOIN DayEndStockItemLnk ON aCompany.Company_DayEndID = DayEndStockItemLnk.DayEndStockItemLnk_DayEndID SET DayEndStockItemLnk.DayEndStockItemLnk_QuantitySales = 0, DayEndStockItemLnk.DayEndStockItemLnk_QuantityGRV = 0;"); //Multi Warehouse change //cnnDBreport.Execute "UPDATE aConsignment AS aConsignment_1 RIGHT JOIN (aConsignment RIGHT JOIN ((DayEndStockItemLnk INNER JOIN (Sale INNER JOIN aCompany ON Sale.Sale_DayEndID = aCompany.Company_DayEndID) ON DayEndStockItemLnk.DayEndStockItemLnk_DayEndID = aCompany.Company_DayEndID) INNER JOIN SaleItem ON (DayEndStockItemLnk.DayEndStockItemLnk_StockItemID = SaleItem.SaleItem_StockItemID) AND (Sale.SaleID = SaleItem.SaleItem_SaleID)) ON aConsignment.Consignment_SaleID = Sale.SaleID) ON aConsignment_1.Consignment_ReversalSaleID = Sale.SaleID SET DayEndStockItemLnk.DayEndStockItemLnk_QuantitySales = [DayEndStockItemLnk]![DayEndStockItemLnk_QuantitySales]+(IIf([SaleItem_Reversal],0-[SaleItem_ShrinkQuantity]*[SaleItem_Quantity],[SaleItem_ShrinkQuantity]*[SaleItem_Quantity])) WHERE (((SaleItem.SaleItem_Recipe)=0) AND ((SaleItem.SaleItem_Revoke)=0) AND ((SaleItem.SaleItem_DepositType)=0) AND ((aConsignment.ConsignmentID) Is Null) AND ((aConsignment_1.ConsignmentID) Is Null));" sql = "UPDATE aConsignment AS aConsignment_1 RIGHT JOIN (aConsignment RIGHT JOIN ((DayEndStockItemLnk INNER JOIN (Sale INNER JOIN aCompany ON Sale.Sale_DayEndID = aCompany.Company_DayEndID) ON DayEndStockItemLnk.DayEndStockItemLnk_DayEndID = aCompany.Company_DayEndID) INNER JOIN SaleItem ON (DayEndStockItemLnk.DayEndStockItemLnk_StockItemID = SaleItem.SaleItem_StockItemID) AND (DayEndStockItemLnk.DayEndStockItemLnk_Warehouse = SaleItem.SaleItem_WarehouseID) AND (Sale.SaleID = SaleItem.SaleItem_SaleID)) ON aConsignment.Consignment_SaleID = Sale.SaleID) ON aConsignment_1.Consignment_ReversalSaleID = Sale.SaleID SET DayEndStockItemLnk.DayEndStockItemLnk_QuantitySales = [DayEndStockItemLnk]![DayEndStockItemLnk_QuantitySales]+(IIf([SaleItem_Reversal],0-[SaleItem_ShrinkQuantity]*[SaleItem_Quantity],[SaleItem_ShrinkQuantity]*[SaleItem_Quantity])) "; sql = sql + "WHERE (((SaleItem.SaleItem_Recipe)=0) AND ((SaleItem.SaleItem_Revoke)=0) AND ((SaleItem.SaleItem_DepositType)=0) AND ((aConsignment.ConsignmentID) Is Null) AND ((aConsignment_1.ConsignmentID) Is Null));"; modReport.cnnDBreport.Execute(sql); //sql = "UPDATE aSaleItemReciept INNER JOIN (aConsignment AS aConsignment_1 RIGHT JOIN (aConsignment RIGHT JOIN ((DayEndStockItemLnk INNER JOIN (Sale INNER JOIN aCompany ON Sale.Sale_DayEndID = aCompany.Company_DayEndID) ON DayEndStockItemLnk.DayEndStockItemLnk_DayEndID = aCompany.Company_DayEndID) INNER JOIN SaleItem ON Sale.SaleID = SaleItem.SaleItem_SaleID) ON aConsignment.Consignment_SaleID = Sale.SaleID) ON aConsignment_1.Consignment_ReversalSaleID = Sale.SaleID) ON (aSaleItemReciept.SaleItemReciept_StockitemID = DayEndStockItemLnk.DayEndStockItemLnk_StockItemID) AND (aSaleItemReciept.SaleItemReciept_SaleItemID = SaleItem.SaleItemID) SET DayEndStockItemLnk.DayEndStockItemLnk_QuantitySales = [DayEndStockItemLnk]![DayEndStockItemLnk_QuantitySales]+(IIf([SaleItem_Reversal],0-[SaleItemReciept_Quantity]*[SaleItem_Quantity],[SaleItemReciept_Quantity]*[SaleItem_Quantity])) " //sql = sql & "WHERE (((SaleItem.SaleItem_Recipe)<>0) AND ((SaleItem.SaleItem_Revoke)=0) AND ((SaleItem.SaleItem_DepositType)=0) AND ((aConsignment.ConsignmentID) Is Null) AND ((aConsignment_1.ConsignmentID) Is Null));" sql = "UPDATE aSaleItemReciept INNER JOIN (aConsignment AS aConsignment_1 RIGHT JOIN (aConsignment RIGHT JOIN ((DayEndStockItemLnk INNER JOIN (Sale INNER JOIN aCompany ON Sale.Sale_DayEndID = aCompany.Company_DayEndID) ON DayEndStockItemLnk.DayEndStockItemLnk_DayEndID = aCompany.Company_DayEndID) INNER JOIN SaleItem ON Sale.SaleID = SaleItem.SaleItem_SaleID AND DayEndStockItemLnk.DayEndStockItemLnk_Warehouse = SaleItem.SaleItem_WarehouseID) ON aConsignment.Consignment_SaleID = Sale.SaleID) ON aConsignment_1.Consignment_ReversalSaleID = Sale.SaleID) ON (aSaleItemReciept.SaleItemReciept_StockitemID = DayEndStockItemLnk.DayEndStockItemLnk_StockItemID) AND (aSaleItemReciept.SaleItemReciept_SaleItemID = SaleItem.SaleItemID) SET DayEndStockItemLnk.DayEndStockItemLnk_QuantitySales = [DayEndStockItemLnk]![DayEndStockItemLnk_QuantitySales]+(IIf([SaleItem_Reversal],0-[SaleItemReciept_Quantity]*[SaleItem_Quantity],[SaleItemReciept_Quantity]*[SaleItem_Quantity])) "; sql = sql + "WHERE (((SaleItem.SaleItem_Recipe)<>0) AND ((SaleItem.SaleItem_Revoke)=0) AND ((SaleItem.SaleItem_DepositType)=0) AND ((aConsignment.ConsignmentID) Is Null) AND ((aConsignment_1.ConsignmentID) Is Null));"; modReport.cnnDBreport.Execute(sql); //Multi Warehouse change modReport.cnnDBreport.Execute("UPDATE aGRV INNER JOIN ((aCompany INNER JOIN DayEndStockItemLnk ON aCompany.Company_DayEndID = DayEndStockItemLnk.DayEndStockItemLnk_DayEndID) INNER JOIN aGRVItem ON DayEndStockItemLnk.DayEndStockItemLnk_StockItemID = aGRVItem.GRVItem_StockItemID) ON (DayEndStockItemLnk.DayEndStockItemLnk_DayEndID = aGRV.GRV_DayEndID) AND (aGRV.GRVID = aGRVItem.GRVItem_GRVID) SET DayEndStockItemLnk.DayEndStockItemLnk_QuantityGRV = [DayEndStockItemLnk_QuantityGRV]+IIf([aGRVItem]![GRVItem_Return],0-[GRVItem_PackSize]*[GRVItem_Quantity],[GRVItem_PackSize]*[GRVItem_Quantity]) WHERE (((aGRV.GRV_GRVStatusID)=3));"); } System.Windows.Forms.Application.DoEvents(); this.Close(); return; Err_beginUpdate: Interaction.MsgBox("Error while Loading Report and Error is :" + Err().Number + " " + Err().Description + " " + Err().Source); System.Windows.Forms.Application.DoEvents(); this.Close(); } private void frmUpdateDayEnd_Load(System.Object eventSender, System.EventArgs eventArgs) { picInner.Width = 0; } private void tmrStart_Tick(System.Object eventSender, System.EventArgs eventArgs) { tmrStart.Enabled = false; beginUpdate(); } } }
using Braintree.Exceptions; using Braintree.Test; using Braintree.TestUtil; using NUnit.Framework; using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Braintree.Tests.Integration { [TestFixture] public class CreditCardIntegrationTest { private BraintreeGateway gateway; private BraintreeService service; [SetUp] public void Setup() { gateway = new BraintreeGateway { Environment = Environment.DEVELOPMENT, MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; service = new BraintreeService(gateway.Configuration); } public void FraudProtectionEnterpriseSetup() { gateway = new BraintreeGateway { Environment = Environment.DEVELOPMENT, MerchantId = "fraud_protection_enterprise_integration_merchant_id", PublicKey = "fraud_protection_enterprise_integration_public_key", PrivateKey = "fraud_protection_enterprise_integration_private_key" }; service = new BraintreeService(gateway.Configuration); } [Test] public void Create_CreatesCreditCardForGivenCustomerId() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo", BillingAddress = new CreditCardAddressRequest { FirstName = "John", CountryName = "Chad", CountryCodeAlpha2 = "TD", CountryCodeAlpha3 = "TCD", CountryCodeNumeric = "148" } }; CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target; Assert.AreEqual("510510", creditCard.Bin); Assert.AreEqual("5100", creditCard.LastFour); Assert.AreEqual("510510******5100", creditCard.MaskedNumber); Assert.AreEqual("05", creditCard.ExpirationMonth); Assert.AreEqual("2012", creditCard.ExpirationYear); Assert.AreEqual("Michael Angelo", creditCard.CardholderName); Assert.IsTrue(creditCard.IsDefault.Value); Assert.IsFalse(creditCard.IsVenmoSdk.Value); Assert.AreEqual(DateTime.Now.Year, creditCard.CreatedAt.Value.Year); Assert.AreEqual(DateTime.Now.Year, creditCard.UpdatedAt.Value.Year); Assert.IsNotNull(creditCard.ImageUrl); Address billingAddress = creditCard.BillingAddress; Assert.AreEqual("Chad", billingAddress.CountryName); Assert.AreEqual("TD", billingAddress.CountryCodeAlpha2); Assert.AreEqual("TCD", billingAddress.CountryCodeAlpha3); Assert.AreEqual("148", billingAddress.CountryCodeNumeric); Assert.IsTrue(Regex.IsMatch(creditCard.UniqueNumberIdentifier, "\\A\\w{32}\\z")); } [Test] #if netcore public async Task CreateAsync_CreatesCreditCardForGivenCustomerId() #else public void CreateAsync_CreatesCreditCardForGivenCustomerId() { Task.Run(async () => #endif { Result<Customer> customerResult = await gateway.Customer.CreateAsync(new CustomerRequest()); Customer customer = customerResult.Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo", BillingAddress = new CreditCardAddressRequest { FirstName = "John", CountryName = "Chad", CountryCodeAlpha2 = "TD", CountryCodeAlpha3 = "TCD", CountryCodeNumeric = "148" } }; Result<CreditCard> creditCardResult = await gateway.CreditCard.CreateAsync(creditCardRequest); CreditCard creditCard = creditCardResult.Target; Assert.AreEqual("510510", creditCard.Bin); Assert.AreEqual("5100", creditCard.LastFour); Assert.AreEqual("510510******5100", creditCard.MaskedNumber); Assert.AreEqual("05", creditCard.ExpirationMonth); Assert.AreEqual("2012", creditCard.ExpirationYear); Assert.AreEqual("Michael Angelo", creditCard.CardholderName); Assert.IsTrue(creditCard.IsDefault.Value); Assert.IsFalse(creditCard.IsVenmoSdk.Value); Assert.AreEqual(DateTime.Now.Year, creditCard.CreatedAt.Value.Year); Assert.AreEqual(DateTime.Now.Year, creditCard.UpdatedAt.Value.Year); Assert.IsNotNull(creditCard.ImageUrl); Address billingAddress = creditCard.BillingAddress; Assert.AreEqual("Chad", billingAddress.CountryName); Assert.AreEqual("TD", billingAddress.CountryCodeAlpha2); Assert.AreEqual("TCD", billingAddress.CountryCodeAlpha3); Assert.AreEqual("148", billingAddress.CountryCodeNumeric); Assert.IsTrue(Regex.IsMatch(creditCard.UniqueNumberIdentifier, "\\A\\w{32}\\z")); } #if net452 ).GetAwaiter().GetResult(); } #endif [Test] public void Create_CreatesCreditCardWithAVenmoSdkPaymentMethodCode() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, VenmoSdkPaymentMethodCode = SandboxValues.VenmoSdk.VISA_PAYMENT_METHOD_CODE, }; Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest); Assert.IsTrue(result.IsSuccess()); CreditCard creditCard = result.Target; Assert.AreEqual("1111", creditCard.LastFour); Assert.IsFalse(creditCard.IsVenmoSdk.Value); } [Test] [Obsolete] public void Create_CreatesCreditCardWithSecurityParams() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, DeviceSessionId = "abc123", FraudMerchantId = "7", CardholderName = "John Doe", Number = "5105105105105100", ExpirationDate = "05/12", BillingAddress = new CreditCardAddressRequest { CountryName = "Greece", CountryCodeAlpha2 = "GR", CountryCodeAlpha3 = "GRC", CountryCodeNumeric = "300" } }; Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest); Assert.IsTrue(result.IsSuccess()); } [Test] public void Create_CreatesCreditCardWithDeviceData() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, DeviceData = "{\"device_session_id\":\"my_dsid\", \"fraud_merchant_id\":\"7\"}", CardholderName = "John Doe", Number = "5105105105105100", ExpirationDate = "05/12", BillingAddress = new CreditCardAddressRequest { CountryName = "Greece", CountryCodeAlpha2 = "GR", CountryCodeAlpha3 = "GRC", CountryCodeNumeric = "300" } }; Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest); Assert.IsTrue(result.IsSuccess()); } [Test] public void Create_FailsToCreateCreditCardWithInvalidVenmoSdkPaymentMethodCode() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, VenmoSdkPaymentMethodCode = SandboxValues.VenmoSdk.INVALID_PAYMENT_METHOD_CODE, }; Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest); Assert.IsFalse(result.IsSuccess()); Assert.AreEqual("Invalid VenmoSDK payment method code", result.Message); Assert.AreEqual( ValidationErrorCode.CREDIT_CARD_INVALID_VENMO_SDK_PAYMENT_METHOD_CODE, result.Errors.ForObject("CreditCard").OnField("VenmoSdkPaymentMethodCode")[0].Code ); } [Test] public void Create_AddsCardToVenmoSdkWithValidSession() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VenmoSdkSession = SandboxValues.VenmoSdk.SESSION } }; Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest); CreditCard card = result.Target; Assert.IsTrue(result.IsSuccess()); Assert.IsFalse(card.IsVenmoSdk.Value); } [Test] public void Create_DoesNotAddCardToVenmoSdkWithInvalidSession() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VenmoSdkSession = SandboxValues.VenmoSdk.INVALID_SESSION } }; Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest); CreditCard card = result.Target; Assert.IsTrue(result.IsSuccess()); Assert.IsFalse(card.IsVenmoSdk.Value); } [Test] public void Create_AcceptsBillingAddressId() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; AddressRequest addressRequest = new AddressRequest { FirstName = "John", CountryName = "Chad", CountryCodeAlpha2 = "TD", CountryCodeAlpha3 = "TCD", CountryCodeNumeric = "148" }; Address address = gateway.Address.Create(customer.Id, addressRequest).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo", BillingAddressId = address.Id }; CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target; Address billingAddress = creditCard.BillingAddress; Assert.AreEqual(address.Id, billingAddress.Id); Assert.AreEqual("Chad", billingAddress.CountryName); Assert.AreEqual("TD", billingAddress.CountryCodeAlpha2); Assert.AreEqual("TCD", billingAddress.CountryCodeAlpha3); Assert.AreEqual("148", billingAddress.CountryCodeNumeric); } [Test] public void Find_FindsCreditCardByToken() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo" }; CreditCard originalCreditCard = gateway.CreditCard.Create(creditCardRequest).Target; CreditCard creditCard = gateway.CreditCard.Find(originalCreditCard.Token); Assert.AreEqual("510510", creditCard.Bin); Assert.AreEqual("5100", creditCard.LastFour); Assert.AreEqual("05", creditCard.ExpirationMonth); Assert.AreEqual("2012", creditCard.ExpirationYear); Assert.AreEqual("Michael Angelo", creditCard.CardholderName); Assert.AreEqual(DateTime.Now.Year, creditCard.CreatedAt.Value.Year); Assert.AreEqual(DateTime.Now.Year, creditCard.UpdatedAt.Value.Year); } [Test] #if netcore public async Task FindAsync_FindsCreditCardByToken() #else public void FindAsync_FindsCreditCardByToken() { Task.Run(async () => #endif { Result<Customer> customerResult = await gateway.Customer.CreateAsync(new CustomerRequest()); Customer customer = customerResult.Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo" }; Result<CreditCard> originalCreditCardResult = await gateway.CreditCard.CreateAsync(creditCardRequest); CreditCard originalCreditCard = originalCreditCardResult.Target; CreditCard creditCard = await gateway.CreditCard.FindAsync(originalCreditCard.Token); Assert.AreEqual("510510", creditCard.Bin); Assert.AreEqual("5100", creditCard.LastFour); Assert.AreEqual("05", creditCard.ExpirationMonth); Assert.AreEqual("2012", creditCard.ExpirationYear); Assert.AreEqual("Michael Angelo", creditCard.CardholderName); Assert.AreEqual(DateTime.Now.Year, creditCard.CreatedAt.Value.Year); Assert.AreEqual(DateTime.Now.Year, creditCard.UpdatedAt.Value.Year); } #if net452 ).GetAwaiter().GetResult(); } #endif [Test] public void Find_FindsAssociatedSubscriptions() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123" }; CreditCard originalCreditCard = gateway.CreditCard.Create(creditCardRequest).Target; string id = Guid.NewGuid().ToString(); var subscriptionRequest = new SubscriptionRequest { Id = id, PlanId = "integration_trialless_plan", PaymentMethodToken = originalCreditCard.Token, Price = 1.00M }; gateway.Subscription.Create(subscriptionRequest); CreditCard creditCard = gateway.CreditCard.Find(originalCreditCard.Token); Subscription subscription = creditCard.Subscriptions[0]; Assert.AreEqual(id, subscription.Id); Assert.AreEqual("integration_trialless_plan", subscription.PlanId); Assert.AreEqual(1.00M, subscription.Price); } [Test] public void FromNonce_ExchangesANonceForACreditCard() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; string nonce = TestHelper.GenerateUnlockedNonce(gateway, "4012888888881881", customer.Id); CreditCard card = gateway.CreditCard.FromNonce(nonce); Assert.AreEqual("401288******1881", card.MaskedNumber); } [Test] #if netcore public async Task FromNonceAsync_ExchangesANonceForACreditCard() #else public void FromNonceAsync_ExchangesANonceForACreditCard() { Task.Run(async () => #endif { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; string nonce = TestHelper.GenerateUnlockedNonce(gateway, "4012888888881881", customer.Id); CreditCard card = await gateway.CreditCard.FromNonceAsync(nonce); Assert.AreEqual("401288******1881", card.MaskedNumber); } #if net452 ).GetAwaiter().GetResult(); } #endif [Test] public void FromNonce_ReturnsErrorWhenProvidedNoncePointingToUnlockedSharedCard() { string nonce = TestHelper.GenerateUnlockedNonce(gateway); Exception exception = null; try { gateway.CreditCard.FromNonce(nonce); } catch (Exception tempException) { exception = tempException; } Assert.IsNotNull(exception); StringAssert.Contains("not found", exception.Message); Assert.IsInstanceOf(typeof(NotFoundException), exception); } [Test] #if netcore public async Task FromNonceAsync_ReturnsErrorWhenProvidedNoncePointingToUnlockedSharedCard() #else public void FromNonceAsync_ReturnsErrorWhenProvidedNoncePointingToUnlockedSharedCard() { Task.Run(async () => #endif { string nonce = TestHelper.GenerateUnlockedNonce(gateway); Exception exception = null; try { await gateway.CreditCard.FromNonceAsync(nonce); } catch (Exception tempException) { exception = tempException; } Assert.IsNotNull(exception); StringAssert.Contains("not found", exception.Message); Assert.IsInstanceOf(typeof(NotFoundException), exception); } #if net452 ).GetAwaiter().GetResult(); } #endif [Test] public void FromNonce_ReturnsErrorWhenProvidedConsumedNonce() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; string nonce = TestHelper.GenerateUnlockedNonce(gateway, "4012888888881881", customer.Id); gateway.CreditCard.FromNonce(nonce); Exception exception = null; try { gateway.CreditCard.FromNonce(nonce); } catch (Exception tempException) { exception = tempException; } StringAssert.Contains("consumed", exception.Message); Assert.IsNotNull(exception); Assert.IsInstanceOf(typeof(NotFoundException), exception); } [Test] #if netcore public async Task FromNonceAsync_ReturnsErrorWhenProvidedConsumedNonce() #else public void FromNonceAsync_ReturnsErrorWhenProvidedConsumedNonce() { Task.Run(async () => #endif { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; string nonce = TestHelper.GenerateUnlockedNonce(gateway, "4012888888881881", customer.Id); await gateway.CreditCard.FromNonceAsync(nonce); Exception exception = null; try { await gateway.CreditCard.FromNonceAsync(nonce); } catch (Exception tempException) { exception = tempException; } StringAssert.Contains("consumed", exception.Message); Assert.IsNotNull(exception); Assert.IsInstanceOf(typeof(NotFoundException), exception); } #if net452 ).GetAwaiter().GetResult(); } #endif [Test] public void Update_UpdatesCreditCardByToken() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardCreateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo" }; CreditCard originalCreditCard = gateway.CreditCard.Create(creditCardCreateRequest).Target; var creditCardUpdateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "4111111111111111", ExpirationDate = "12/05", CVV = "321", CardholderName = "Dave Inchy" }; CreditCard creditCard = gateway.CreditCard.Update(originalCreditCard.Token, creditCardUpdateRequest).Target; Assert.AreEqual("411111", creditCard.Bin); Assert.AreEqual("1111", creditCard.LastFour); Assert.AreEqual("12", creditCard.ExpirationMonth); Assert.AreEqual("2005", creditCard.ExpirationYear); Assert.AreEqual("Dave Inchy", creditCard.CardholderName); Assert.AreEqual(DateTime.Now.Year, creditCard.CreatedAt.Value.Year); Assert.AreEqual(DateTime.Now.Year, creditCard.UpdatedAt.Value.Year); } [Test] #if netcore public async Task UpdateAsync_UpdatesCreditCardByToken() #else public void UpdateAsync_UpdatesCreditCardByToken() { Task.Run(async () => #endif { Result<Customer> customerResult = await gateway.Customer.CreateAsync(new CustomerRequest()); Customer customer = customerResult.Target; var creditCardCreateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo" }; Result<CreditCard> originalCreditCardResult = await gateway.CreditCard.CreateAsync(creditCardCreateRequest); CreditCard originalCreditCard = originalCreditCardResult.Target; var creditCardUpdateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "4111111111111111", ExpirationDate = "12/05", CVV = "321", CardholderName = "Dave Inchy" }; Result<CreditCard> creditCardUpdateResult = await gateway.CreditCard.UpdateAsync(originalCreditCard.Token, creditCardUpdateRequest); CreditCard creditCard = creditCardUpdateResult.Target; Assert.AreEqual("411111", creditCard.Bin); Assert.AreEqual("1111", creditCard.LastFour); Assert.AreEqual("12", creditCard.ExpirationMonth); Assert.AreEqual("2005", creditCard.ExpirationYear); Assert.AreEqual("Dave Inchy", creditCard.CardholderName); Assert.AreEqual(DateTime.Now.Year, creditCard.CreatedAt.Value.Year); Assert.AreEqual(DateTime.Now.Year, creditCard.UpdatedAt.Value.Year); } #if net452 ).GetAwaiter().GetResult(); } #endif [Test] public void Create_SetsDefaultIfSpecified() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var request1 = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo" }; var request2 = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo", Options = new CreditCardOptionsRequest { MakeDefault = true }, }; CreditCard card1 = gateway.CreditCard.Create(request1).Target; CreditCard card2 = gateway.CreditCard.Create(request2).Target; Assert.IsFalse(gateway.CreditCard.Find(card1.Token).IsDefault.Value); Assert.IsTrue(gateway.CreditCard.Find(card2.Token).IsDefault.Value); } [Test] public void Update_UpdatesDefaultIfSpecified() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardCreateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo" }; CreditCard card1 = gateway.CreditCard.Create(creditCardCreateRequest).Target; CreditCard card2 = gateway.CreditCard.Create(creditCardCreateRequest).Target; Assert.IsTrue(card1.IsDefault.Value); Assert.IsFalse(card2.IsDefault.Value); var creditCardUpdateRequest = new CreditCardRequest { Options = new CreditCardOptionsRequest { MakeDefault = true } }; gateway.CreditCard.Update(card2.Token, creditCardUpdateRequest); Assert.IsFalse(gateway.CreditCard.Find(card1.Token).IsDefault.Value); Assert.IsTrue(gateway.CreditCard.Find(card2.Token).IsDefault.Value); } [Test] public void Update_CreatesNewBillingAddressByDefault() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var request = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", BillingAddress = new CreditCardAddressRequest { FirstName = "John" } }; CreditCard creditCard = gateway.CreditCard.Create(request).Target; var updateRequest = new CreditCardRequest { BillingAddress = new CreditCardAddressRequest { LastName = "Jones", CountryName = "El Salvador", CountryCodeAlpha2 = "SV", CountryCodeAlpha3 = "SLV", CountryCodeNumeric = "222" } }; CreditCard updatedCreditCard = gateway.CreditCard.Update(creditCard.Token, updateRequest).Target; Assert.IsNull(updatedCreditCard.BillingAddress.FirstName); Assert.AreEqual("Jones", updatedCreditCard.BillingAddress.LastName); Assert.AreNotEqual(creditCard.BillingAddress.Id, updatedCreditCard.BillingAddress.Id); Address billingAddress = updatedCreditCard.BillingAddress; Assert.AreEqual("El Salvador", billingAddress.CountryName); Assert.AreEqual("SV", billingAddress.CountryCodeAlpha2); Assert.AreEqual("SLV", billingAddress.CountryCodeAlpha3); Assert.AreEqual("222", billingAddress.CountryCodeNumeric); } [Test] public void Update_UpdatesExistingBillingAddressWhenUpdateExistingIsTrue() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var request = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", BillingAddress = new CreditCardAddressRequest { FirstName = "John" } }; CreditCard creditCard = gateway.CreditCard.Create(request).Target; var updateRequest = new CreditCardRequest { BillingAddress = new CreditCardAddressRequest { LastName = "Jones", Options = new CreditCardAddressOptionsRequest { UpdateExisting = true } } }; CreditCard updatedCreditCard = gateway.CreditCard.Update(creditCard.Token, updateRequest).Target; Assert.AreEqual("John", updatedCreditCard.BillingAddress.FirstName); Assert.AreEqual("Jones", updatedCreditCard.BillingAddress.LastName); Assert.AreEqual(creditCard.BillingAddress.Id, updatedCreditCard.BillingAddress.Id); } [Test] public void Update_CheckDuplicateCreditCard() { var customer = new CustomerRequest { CreditCard = new CreditCardRequest { Number = "4111111111111111", ExpirationDate = "05/12", } }; var dupCustomer = new CustomerRequest { CreditCard = new CreditCardRequest { Number = "4111111111111111", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { FailOnDuplicatePaymentMethod = true } } }; var createResult = gateway.Customer.Create(customer); Assert.IsTrue(createResult.IsSuccess()); var updateResult = gateway.Customer.Update(createResult.Target.Id, dupCustomer); Assert.IsFalse(updateResult.IsSuccess()); Assert.AreEqual( ValidationErrorCode.CREDIT_CARD_DUPLICATE_CARD_EXISTS, updateResult.Errors.ForObject("Customer").ForObject("CreditCard").OnField("Number")[0].Code ); } [Test] public void Delete_DeletesTheCreditCard() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo" }; CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target; Assert.AreEqual(creditCard.Token, gateway.CreditCard.Find(creditCard.Token).Token); gateway.CreditCard.Delete(creditCard.Token); Assert.Throws<NotFoundException>(() => gateway.CreditCard.Find(creditCard.Token)); } [Test] #if netcore public async Task DeleteAsync_DeletesTheCreditCard() #else public void DeleteAsync_DeletesTheCreditCard() { Task.Run(async () => #endif { Result<Customer> customerResult = await gateway.Customer.CreateAsync(new CustomerRequest()); Customer customer = customerResult.Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo" }; Result<CreditCard> creditCardResult = await gateway.CreditCard.CreateAsync(creditCardRequest); CreditCard creditCard = creditCardResult.Target; Assert.AreEqual(creditCard.Token, gateway.CreditCard.Find(creditCard.Token).Token); await gateway.CreditCard.DeleteAsync(creditCard.Token); Assert.Throws<NotFoundException>(() => gateway.CreditCard.Find(creditCard.Token)); } #if net452 ).GetAwaiter().GetResult(); } #endif [Test] public void CheckDuplicateCreditCard() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "4111111111111111", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { FailOnDuplicatePaymentMethod = true } }; gateway.CreditCard.Create(request); Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsFalse(result.IsSuccess()); Assert.AreEqual( ValidationErrorCode.CREDIT_CARD_DUPLICATE_CARD_EXISTS, result.Errors.ForObject("CreditCard").OnField("Number")[0].Code ); } [Test] public void VerifyValidCreditCard() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "4111111111111111", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsTrue(result.IsSuccess()); } [Test] public void VerifyValidCreditCardWithVerificationRiskData() { FraudProtectionEnterpriseSetup(); Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "4111111111111111", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true }, DeviceData = "{\"device_session_id\":\"my_dsid\", \"fraud_merchant_id\":\"7\"}" }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsTrue(result.IsSuccess()); CreditCard card = result.Target; CreditCardVerification verification = card.Verification; Assert.IsNotNull(verification); Assert.IsNotNull(verification.RiskData); Assert.IsNotNull(verification.RiskData.decision); Assert.IsNotNull(verification.RiskData.DecisionReasons); Assert.IsNotNull(verification.RiskData.id); } [Test] public void VerifyValidCreditCardWithVerificationAmount() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "4111111111111111", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true, VerificationAmount = "1.02" } }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsTrue(result.IsSuccess()); } [Test] public void VerifyValidCreditCardSpecifyingMerhantAccount() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "5105105105105100", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true, VerificationMerchantAccountId = MerchantAccountIDs.NON_DEFAULT_MERCHANT_ACCOUNT_ID } }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsFalse(result.IsSuccess()); Assert.AreEqual(MerchantAccountIDs.NON_DEFAULT_MERCHANT_ACCOUNT_ID, result.CreditCardVerification.MerchantAccountId); } [Test] public void VerifyInvalidCreditCard() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "5105105105105100", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsFalse(result.IsSuccess()); CreditCardVerification verification = result.CreditCardVerification; Assert.AreEqual(VerificationStatus.PROCESSOR_DECLINED, verification.Status); Assert.IsNull(verification.GatewayRejectionReason); } [Test] public void GatewayRejectionReason_ExposedOnVerification() { BraintreeGateway processingRulesGateway = new BraintreeGateway { Environment = Environment.DEVELOPMENT, MerchantId = "processing_rules_merchant_id", PublicKey = "processing_rules_public_key", PrivateKey = "processing_rules_private_key" }; Customer customer = processingRulesGateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "200", Number = "4111111111111111", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; Result<CreditCard> result = processingRulesGateway.CreditCard.Create(request); Assert.IsFalse(result.IsSuccess()); CreditCardVerification verification = result.CreditCardVerification; Assert.AreEqual(TransactionGatewayRejectionReason.CVV, verification.GatewayRejectionReason); } [Test] public void CreateWithoutSkipAdvancedFraudCheckingIncludesRiskData() { FraudProtectionEnterpriseSetup(); Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "4111111111111111", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true, SkipAdvancedFraudChecking = false }, }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsTrue(result.IsSuccess()); CreditCardVerification verification = result.Target.Verification; Assert.IsNotNull(verification); Assert.IsNotNull(verification.RiskData); } [Test] public void CreateWithSkipAdvancedFraudCheckingDoesNotIncludeRiskData() { FraudProtectionEnterpriseSetup(); Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "4111111111111111", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true, SkipAdvancedFraudChecking = true }, }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsTrue(result.IsSuccess()); CreditCardVerification verification = result.Target.Verification; Assert.IsNotNull(verification); Assert.IsNull(verification.RiskData); } [Test] public void Expired() { ResourceCollection<CreditCard> collection = gateway.CreditCard.Expired(); Assert.IsTrue(collection.MaximumCount > 1); List<string> cards = new List<string>(); foreach (CreditCard card in collection) { Assert.IsTrue(card.IsExpired.Value); cards.Add(card.Token); } HashSet<string> uniqueCards = new HashSet<string>(cards); Assert.AreEqual(uniqueCards.Count, collection.MaximumCount); } [Test] public void ExpiringBetween() { DateTime beginning = new DateTime(2010, 1, 1); DateTime end = new DateTime(2010, 12, 31); ResourceCollection<CreditCard> collection = gateway.CreditCard.ExpiringBetween(beginning, end); Assert.IsTrue(collection.MaximumCount > 1); List<string> cards = new List<string>(); foreach (CreditCard card in collection) { Assert.AreEqual("2010", card.ExpirationYear); cards.Add(card.Token); } HashSet<string> uniqueCards = new HashSet<string>(cards); Assert.AreEqual(uniqueCards.Count, collection.MaximumCount); } [Test] #if netcore public async Task ExpiringBetweenAsync() #else public void ExpiringBetweenAsync() { Task.Run(async () => #endif { DateTime beginning = new DateTime(2010, 1, 1); DateTime end = new DateTime(2010, 12, 31); ResourceCollection<CreditCard> collection = await gateway.CreditCard.ExpiringBetweenAsync(beginning, end); Assert.IsTrue(collection.MaximumCount > 1); List<string> cards = new List<string>(); foreach (CreditCard card in collection) { Assert.AreEqual("2010", card.ExpirationYear); cards.Add(card.Token); } HashSet<string> uniqueCards = new HashSet<string>(cards); Assert.AreEqual(uniqueCards.Count, collection.MaximumCount); } #if net452 ).GetAwaiter().GetResult(); } #endif [Test] public void Prepaid() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = TestUtil.CreditCardNumbers.CardTypeIndicators.Prepaid, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; CreditCard creditCard = gateway.CreditCard.Create(request).Target; Assert.AreEqual(CreditCardPrepaid.YES, creditCard.Prepaid); } [Test] public void Commercial() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = TestUtil.CreditCardNumbers.CardTypeIndicators.Commercial, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; CreditCard creditCard = gateway.CreditCard.Create(request).Target; Assert.AreEqual(CreditCardCommercial.YES, creditCard.Commercial); } [Test] public void Debit() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = TestUtil.CreditCardNumbers.CardTypeIndicators.Debit, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; CreditCard creditCard = gateway.CreditCard.Create(request).Target; Assert.AreEqual(CreditCardDebit.YES, creditCard.Debit); } [Test] public void Healthcare() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = TestUtil.CreditCardNumbers.CardTypeIndicators.Healthcare, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; CreditCard creditCard = gateway.CreditCard.Create(request).Target; Assert.AreEqual(CreditCardHealthcare.YES, creditCard.Healthcare); Assert.AreEqual("J3", creditCard.ProductId); } [Test] public void Payroll() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = TestUtil.CreditCardNumbers.CardTypeIndicators.Payroll, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; CreditCard creditCard = gateway.CreditCard.Create(request).Target; Assert.AreEqual(CreditCardPayroll.YES, creditCard.Payroll); Assert.AreEqual("MSA", creditCard.ProductId); } [Test] public void DurbinRegulated() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = TestUtil.CreditCardNumbers.CardTypeIndicators.DurbinRegulated, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; CreditCard creditCard = gateway.CreditCard.Create(request).Target; Assert.AreEqual(CreditCardDurbinRegulated.YES, creditCard.DurbinRegulated); } [Test] public void CountryOfIssuance() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = TestUtil.CreditCardNumbers.CardTypeIndicators.CountryOfIssuance, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; CreditCard creditCard = gateway.CreditCard.Create(request).Target; Assert.AreEqual(TestUtil.CreditCardDefaults.CountryOfIssuance, creditCard.CountryOfIssuance); } [Test] public void IssuingBank() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = TestUtil.CreditCardNumbers.CardTypeIndicators.IssuingBank, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; CreditCard creditCard = gateway.CreditCard.Create(request).Target; Assert.AreEqual(TestUtil.CreditCardDefaults.IssuingBank, creditCard.IssuingBank); } [Test] public void NegativeCardTypeIndicators() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = TestUtil.CreditCardNumbers.CardTypeIndicators.No, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; CreditCard creditCard = gateway.CreditCard.Create(request).Target; Assert.AreEqual(CreditCardPrepaid.NO, creditCard.Prepaid); Assert.AreEqual(CreditCardCommercial.NO, creditCard.Commercial); Assert.AreEqual(CreditCardHealthcare.NO, creditCard.Healthcare); Assert.AreEqual(CreditCardDurbinRegulated.NO, creditCard.DurbinRegulated); Assert.AreEqual(CreditCardPayroll.NO, creditCard.Payroll); Assert.AreEqual(CreditCardDebit.NO, creditCard.Debit); Assert.AreEqual("MSB", creditCard.ProductId); } [Test] public void MissingCardTypeIndicators() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = TestUtil.CreditCardNumbers.CardTypeIndicators.Unknown, ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; CreditCard creditCard = gateway.CreditCard.Create(request).Target; Assert.AreEqual(CreditCardPrepaid.UNKNOWN, creditCard.Prepaid); Assert.AreEqual(CreditCardCommercial.UNKNOWN, creditCard.Commercial); Assert.AreEqual(CreditCardHealthcare.UNKNOWN, creditCard.Healthcare); Assert.AreEqual(CreditCardDurbinRegulated.UNKNOWN, creditCard.DurbinRegulated); Assert.AreEqual(CreditCardPayroll.UNKNOWN, creditCard.Payroll); Assert.AreEqual(CreditCardDebit.UNKNOWN, creditCard.Debit); Assert.AreEqual(CreditCard.CountryOfIssuanceUnknown, creditCard.CountryOfIssuance); Assert.AreEqual(CreditCard.IssuingBankUnknown, creditCard.IssuingBank); Assert.AreEqual(Braintree.CreditCard.ProductIdUnknown, creditCard.ProductId); } [Test] public void CreateWithPaymentMethodNonce() { string nonce = TestHelper.GenerateUnlockedNonce(gateway); Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", PaymentMethodNonce = nonce }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsTrue(result.IsSuccess()); } [Test] public void CreateWithThreeDSecureNonce() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, PaymentMethodNonce = Nonce.ThreeDSecureVisaFullAuthentication, Options = new CreditCardOptionsRequest() { VerifyCard = true }, }; Result<CreditCard> result = gateway.CreditCard.Create(request); CreditCard card = result.Target; CreditCardVerification verification = card.Verification; Assert.AreEqual("Y", verification.ThreeDSecureInfo.Enrolled); Assert.AreEqual("cavv_value", verification.ThreeDSecureInfo.Cavv); Assert.AreEqual("05", verification.ThreeDSecureInfo.EciFlag); Assert.AreEqual("authenticate_successful", verification.ThreeDSecureInfo.Status); Assert.AreEqual("1.0.2", verification.ThreeDSecureInfo.ThreeDSecureVersion); Assert.AreEqual("xid_value", verification.ThreeDSecureInfo.Xid); Assert.IsTrue(verification.ThreeDSecureInfo.LiabilityShifted); Assert.IsTrue(verification.ThreeDSecureInfo.LiabilityShiftPossible); } [Test] public void CreateCreditCardWithInvalidThreeDSecurePassThruParams() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; ThreeDSecurePassThruRequest passThruRequestWithoutThreeDSecureVersion = new ThreeDSecurePassThruRequest() { EciFlag = "05", Cavv = "some_cavv", Xid = "some_xid", AuthenticationResponse = "Y", DirectoryResponse = "Y", CavvAlgorithm = "2", DsTransactionId = "some_ds_transaction_id" }; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, PaymentMethodNonce = Nonce.Transactable, ThreeDSecurePassThru = passThruRequestWithoutThreeDSecureVersion, Options = new CreditCardOptionsRequest() { VerifyCard = true }, }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsFalse(result.IsSuccess()); Assert.AreEqual( ValidationErrorCode.VERIFICATION_THREE_D_SECURE_THREE_D_SECURE_VERSION_IS_REQUIRED, result.Errors.ForObject("Verification").OnField("ThreeDSecureVersion")[0].Code ); } [Test] public void CreateCreditCardWithThreeDSecurePassThruParams() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, PaymentMethodNonce = Nonce.Transactable, ThreeDSecurePassThru = new ThreeDSecurePassThruRequest() { EciFlag = "05", Cavv = "some_cavv", Xid = "some_xid", ThreeDSecureVersion = "2.2.1", AuthenticationResponse = "Y", DirectoryResponse = "Y", CavvAlgorithm = "2", DsTransactionId = "some_ds_transaction_id" }, Options = new CreditCardOptionsRequest() { VerifyCard = true }, }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsTrue(result.IsSuccess()); } [Test] public void Create_WithAccountTypeCredit() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = SandboxValues.CreditCardNumber.HIPER, ExpirationDate = "05/12", CVV = "123", Options = new CreditCardOptionsRequest() { VerifyCard = true, VerificationMerchantAccountId = MerchantAccountIDs.BRAZIL_MERCHANT_ACCOUNT_ID, VerificationAccountType = "credit", }, }; CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target; Assert.AreEqual("credit", creditCard.Verification.CreditCard.AccountType); } [Test] public void Create_WithAccountTypeDebit() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = SandboxValues.CreditCardNumber.HIPER, ExpirationDate = "05/12", CVV = "123", Options = new CreditCardOptionsRequest() { VerifyCard = true, VerificationMerchantAccountId = MerchantAccountIDs.BRAZIL_MERCHANT_ACCOUNT_ID, VerificationAccountType = "debit", }, }; CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target; Assert.AreEqual("debit", creditCard.Verification.CreditCard.AccountType); } [Test] public void Create_WithErrorAccountTypeIsInvalid() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = SandboxValues.CreditCardNumber.HIPER, ExpirationDate = "05/12", CVV = "123", Options = new CreditCardOptionsRequest() { VerifyCard = true, VerificationMerchantAccountId = MerchantAccountIDs.BRAZIL_MERCHANT_ACCOUNT_ID, VerificationAccountType = "ach", }, }; Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest); Assert.IsFalse(result.IsSuccess()); StringAssert.Contains("Verification account type must be either `credit` or `debit`", result.Message); Assert.AreEqual( ValidationErrorCode.CREDIT_CARD_OPTIONS_VERIFICATION_ACCOUNT_TYPE_IS_INVALID, result.Errors.ForObject("CreditCard").ForObject("Options").OnField("VerificationAccountType")[0].Code ); } [Test] public void Create_WithErrorAccountTypeNotSupported() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = SandboxValues.CreditCardNumber.VISA, ExpirationDate = "05/12", CVV = "123", Options = new CreditCardOptionsRequest() { VerifyCard = true, VerificationAccountType = "credit", }, }; Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest); Assert.IsFalse(result.IsSuccess()); StringAssert.Contains("Merchant account does not support verification account type", result.Message); Assert.AreEqual( ValidationErrorCode.CREDIT_CARD_OPTIONS_VERIFICATION_ACCOUNT_TYPE_NOT_SUPPORTED, result.Errors.ForObject("CreditCard").ForObject("Options").OnField("VerificationAccountType")[0].Code ); } [Test] public void UpdateCreditCardWithThreeDSecurePassThruParams() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardCreateRequest = new CreditCardRequest { CustomerId = customer.Id, PaymentMethodNonce = Nonce.Transactable, }; ThreeDSecurePassThruRequest passThruRequestWithThreeDSecureVersion = new ThreeDSecurePassThruRequest() { EciFlag = "05", Cavv = "some_cavv", Xid = "some_xid", ThreeDSecureVersion = "2.2.0", AuthenticationResponse = "Y", DirectoryResponse = "Y", CavvAlgorithm = "2", DsTransactionId = "some_ds_transaction_id" }; CreditCard originalCreditCard = gateway.CreditCard.Create(creditCardCreateRequest).Target; var creditCardUpdateRequest = new CreditCardRequest { CustomerId = customer.Id, PaymentMethodNonce = Nonce.Transactable, ThreeDSecurePassThru = passThruRequestWithThreeDSecureVersion, Options = new CreditCardOptionsRequest() { VerifyCard = true, } }; Result<CreditCard> result = gateway.CreditCard.Update(originalCreditCard.Token, creditCardUpdateRequest); Assert.IsTrue(result.IsSuccess()); } [Test] public void updateCreditCardWithInvalidThreeDSecurePassThruParams() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardCreateRequest = new CreditCardRequest { CustomerId = customer.Id, PaymentMethodNonce = Nonce.Transactable, }; ThreeDSecurePassThruRequest passThruRequestWithoutThreeDSecureVersion = new ThreeDSecurePassThruRequest() { EciFlag = "05", Cavv = "some_cavv", Xid = "some_xid", AuthenticationResponse = "Y", DirectoryResponse = "Y", CavvAlgorithm = "2", DsTransactionId = "some_ds_transaction_id" }; CreditCard originalCreditCard = gateway.CreditCard.Create(creditCardCreateRequest).Target; var creditCardUpdateRequest = new CreditCardRequest { CustomerId = customer.Id, PaymentMethodNonce = Nonce.Transactable, ThreeDSecurePassThru = passThruRequestWithoutThreeDSecureVersion, Options = new CreditCardOptionsRequest() { VerifyCard = true, }, }; Result<CreditCard> result = gateway.CreditCard.Update(originalCreditCard.Token, creditCardUpdateRequest); Assert.IsFalse(result.IsSuccess()); Assert.AreEqual( ValidationErrorCode.VERIFICATION_THREE_D_SECURE_THREE_D_SECURE_VERSION_IS_REQUIRED, result.Errors.ForObject("Verification").OnField("ThreeDSecureVersion")[0].Code ); } [Test] public void UpdateWithoutSkipAdvancedFraudCheckingIncludesRiskData() { FraudProtectionEnterpriseSetup(); Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "4111111111111111", ExpirationDate = "05/12", }; CreditCard originalCreditCard = gateway.CreditCard.Create(request).Target; var creditCardUpdateRequest = new CreditCardRequest { ExpirationDate = "05/22", Options = new CreditCardOptionsRequest { VerifyCard = true, SkipAdvancedFraudChecking = false }, }; Result<CreditCard> result = gateway.CreditCard.Update(originalCreditCard.Token, creditCardUpdateRequest); Assert.IsTrue(result.IsSuccess()); CreditCardVerification verification = result.Target.Verification; Assert.IsNotNull(verification); Assert.IsNotNull(verification.RiskData); } [Test] public void UpdateWithSkipAdvancedFraudCheckingDoesNotIncludeRiskData() { FraudProtectionEnterpriseSetup(); Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "4111111111111111", ExpirationDate = "05/12", }; CreditCard originalCreditCard = gateway.CreditCard.Create(request).Target; var creditCardUpdateRequest = new CreditCardRequest { ExpirationDate = "05/22", Options = new CreditCardOptionsRequest { VerifyCard = true, SkipAdvancedFraudChecking = true }, }; Result<CreditCard> result = gateway.CreditCard.Update(originalCreditCard.Token, creditCardUpdateRequest); Assert.IsTrue(result.IsSuccess()); CreditCardVerification verification = result.Target.Verification; Assert.IsNotNull(verification); Assert.IsNull(verification.RiskData); } [Test] public void Update_WithAccountTypeCredit() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardCreateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = SandboxValues.CreditCardNumber.HIPER, ExpirationDate = "05/12", CVV = "123", }; CreditCard originalCreditCard = gateway.CreditCard.Create(creditCardCreateRequest).Target; var creditCardUpdateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = SandboxValues.CreditCardNumber.HIPER, ExpirationDate = "12/05", CVV = "321", Options = new CreditCardOptionsRequest() { VerifyCard = true, VerificationMerchantAccountId = MerchantAccountIDs.BRAZIL_MERCHANT_ACCOUNT_ID, VerificationAccountType = "credit", }, }; CreditCard creditCard = gateway.CreditCard.Update(originalCreditCard.Token, creditCardUpdateRequest).Target; Assert.AreEqual("credit", creditCard.Verification.CreditCard.AccountType); } [Test] public void Update_WithAccountTypeDebit() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardCreateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = SandboxValues.CreditCardNumber.HIPER, ExpirationDate = "05/12", CVV = "123", }; CreditCard originalCreditCard = gateway.CreditCard.Create(creditCardCreateRequest).Target; var creditCardUpdateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = SandboxValues.CreditCardNumber.HIPER, ExpirationDate = "12/05", CVV = "321", Options = new CreditCardOptionsRequest() { VerifyCard = true, VerificationMerchantAccountId = MerchantAccountIDs.BRAZIL_MERCHANT_ACCOUNT_ID, VerificationAccountType = "debit", }, }; CreditCard creditCard = gateway.CreditCard.Update(originalCreditCard.Token, creditCardUpdateRequest).Target; Assert.AreEqual("debit", creditCard.Verification.CreditCard.AccountType); } [Test] public void Find_WithNetworkTokenizedCard() { CreditCard creditCard = gateway.CreditCard.Find("network_tokenized_credit_card"); Assert.IsTrue(creditCard.IsNetworkTokenized); } [Test] public void Find_WithNonNetworkTokenizedCard() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardCreateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = SandboxValues.CreditCardNumber.VISA, ExpirationDate = "05/12", CVV = "123" }; CreditCard creditCard = gateway.CreditCard.Create(creditCardCreateRequest).Target; CreditCard savedCreditCard = gateway.CreditCard.Find(creditCard.Token); Assert.IsFalse(savedCreditCard.IsNetworkTokenized); } [Test] public void Update_WithMerchantCurrencyOption() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardCreateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = SandboxValues.CreditCardNumber.VISA, ExpirationDate = "05/12", CVV = "123", }; CreditCard originalCreditCard = gateway.CreditCard.Create(creditCardCreateRequest).Target; var creditCardUpdateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = SandboxValues.CreditCardNumber.VISA, ExpirationDate = "12/05", CVV = "321", Options = new CreditCardOptionsRequest() { VerificationCurrencyIsoCode = "USD" }, }; CreditCard creditCard = gateway.CreditCard.Update(originalCreditCard.Token, creditCardUpdateRequest).Target; Assert.AreEqual("1111", creditCard.LastFour); Assert.AreEqual("12", creditCard.ExpirationMonth); Assert.AreEqual("2005", creditCard.ExpirationYear); Assert.AreEqual(DateTime.Now.Year, creditCard.CreatedAt.Value.Year); Assert.AreEqual(DateTime.Now.Year, creditCard.UpdatedAt.Value.Year); } [Test] public void Update_WithInvalidMerchantCurrencyOption() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardCreateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = SandboxValues.CreditCardNumber.VISA, ExpirationDate = "05/12", CVV = "123", }; CreditCard originalCreditCard = gateway.CreditCard.Create(creditCardCreateRequest).Target; var creditCardUpdateRequest = new CreditCardRequest { CustomerId = customer.Id, Number = SandboxValues.CreditCardNumber.VISA, ExpirationDate = "12/05", CVV = "321", Options = new CreditCardOptionsRequest() { VerificationCurrencyIsoCode = "GBP" }, }; Result<CreditCard> updateResult = gateway.CreditCard.Update(originalCreditCard.Token, creditCardUpdateRequest); Assert.IsFalse(updateResult.IsSuccess()); Assert.AreEqual( ValidationErrorCode.CREDIT_CARD_OPTIONS_VERIFICATION_INVALID_PRESENTMENT_CURRENCY, updateResult.Errors.DeepAll()[0].Code ); } [Test] public void Create_WithMerchantCurrencyOption() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", Options = new CreditCardOptionsRequest() { VerificationCurrencyIsoCode = "USD" }, CardholderName = "Michael Angelo", BillingAddress = new CreditCardAddressRequest { FirstName = "John", CountryName = "Chad", CountryCodeAlpha2 = "TD", CountryCodeAlpha3 = "TCD", CountryCodeNumeric = "148" } }; CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target; Assert.AreEqual("510510", creditCard.Bin); Assert.AreEqual("5100", creditCard.LastFour); Assert.AreEqual("510510******5100", creditCard.MaskedNumber); Assert.AreEqual("05", creditCard.ExpirationMonth); Assert.AreEqual("2012", creditCard.ExpirationYear); Assert.AreEqual("Michael Angelo", creditCard.CardholderName); Assert.IsTrue(creditCard.IsDefault.Value); Assert.IsFalse(creditCard.IsVenmoSdk.Value); Assert.AreEqual(DateTime.Now.Year, creditCard.CreatedAt.Value.Year); Assert.AreEqual(DateTime.Now.Year, creditCard.UpdatedAt.Value.Year); Assert.IsNotNull(creditCard.ImageUrl); Address billingAddress = creditCard.BillingAddress; Assert.AreEqual("Chad", billingAddress.CountryName); Assert.AreEqual("TD", billingAddress.CountryCodeAlpha2); Assert.AreEqual("TCD", billingAddress.CountryCodeAlpha3); Assert.AreEqual("148", billingAddress.CountryCodeNumeric); Assert.IsTrue(Regex.IsMatch(creditCard.UniqueNumberIdentifier, "\\A\\w{32}\\z")); } [Test] public void Create_WithInvalidMerchantCurrencyOption() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", Options = new CreditCardOptionsRequest() { VerificationCurrencyIsoCode = "GBP" }, CardholderName = "Michael Angelo", BillingAddress = new CreditCardAddressRequest { FirstName = "John", CountryName = "Chad", CountryCodeAlpha2 = "TD", CountryCodeAlpha3 = "TCD", CountryCodeNumeric = "148" } }; Result<CreditCard> creditCard = gateway.CreditCard.Create(creditCardRequest); Assert.IsFalse(creditCard.IsSuccess()); Assert.AreEqual( ValidationErrorCode.CREDIT_CARD_OPTIONS_VERIFICATION_INVALID_PRESENTMENT_CURRENCY, creditCard.Errors.DeepAll()[0].Code ); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; public class Ball : NetworkBehaviour { public float collisionForceMultiplier = 2.5f; public float minimumVelocity = 10; public float maximumVelocity = 200; private Rigidbody rigidBody = null; private new Renderer renderer = null; private TrailRenderer trailRenderer = null; private Vector3 startingPosition = Vector3.zero; private Coroutine delayCoroutine = null; public float spawnDelay = 3f; // Setting up an event system so that score logic can be contained to a separate script. // https://unity3d.com/learn/tutorials/topics/scripting/events public delegate void BallEventHandler(); public static event BallEventHandler OnTriggerReset; public static event BallEventHandler OnTriggerEnterGoal1; public static event BallEventHandler OnTriggerEnterGoal2; public static event BallEventHandler OnTriggerEnterBumper; public static event BallEventHandler OnTriggerEnterRollover; // Use this for initialization void Start() { renderer = GetComponent<Renderer>(); trailRenderer = GetComponent<TrailRenderer>(); if (!(NetworkManager.singleton.isNetworkActive && NetworkServer.connections.Count == 0)) { rigidBody = GetComponent<Rigidbody>(); startingPosition = transform.position; } ResetBall(); } private void FixedUpdate() { if (NetworkManager.singleton.isNetworkActive && NetworkServer.connections.Count == 0) return; if (rigidBody.velocity == Vector3.zero) { var randDir = UnityEngine.Random.insideUnitCircle.normalized; rigidBody.velocity = new Vector3(randDir.x, 0f, randDir.y); } if (rigidBody.velocity.magnitude < minimumVelocity) { //added a ver small number to keep from dividing by zero rigidBody.velocity = 0.5f * (rigidBody.velocity + rigidBody.velocity.normalized * minimumVelocity); //rigidBody.velocity *= minimumVelocity / rigidBody.velocity.magnitude + 0.000000001F; } if (rigidBody.velocity.magnitude > maximumVelocity) { //added a ver small number to keep from dividing by zero rigidBody.velocity = 0.5f * (rigidBody.velocity + rigidBody.velocity.normalized * maximumVelocity); //rigidBody.velocity *= maximumVelocity / rigidBody.velocity.magnitude + 0.000000001F; } } public void ClampSpeed(float min, float max) { if (NetworkManager.singleton.isNetworkActive && NetworkServer.connections.Count == 0) return; minimumVelocity = min; maximumVelocity = max; } public void UnClampSpeed() { minimumVelocity = 10; maximumVelocity = 200; } public void HideAndPausePhysics() { renderer.enabled = false; trailRenderer.enabled = false; if (NetworkManager.singleton.isNetworkActive && NetworkServer.connections.Count == 0) return; rigidBody.isKinematic = true; } public void ShowAndResumePhysics() { renderer.enabled = true; trailRenderer.enabled = true; if (NetworkManager.singleton.isNetworkActive && NetworkServer.connections.Count == 0) return; rigidBody.isKinematic = false; } private IEnumerator DelayedReset() { yield return new WaitForSeconds(spawnDelay); ShowAndResumePhysics(); ResetPosition(); delayCoroutine = null; } public void ResetBall() { // Check if we are already resetting the ball if (delayCoroutine == null) { HideAndPausePhysics(); if (OnTriggerReset != null) { OnTriggerReset(); } delayCoroutine = StartCoroutine(DelayedReset()); } } public void ResetPosition() { if (NetworkManager.singleton.isNetworkActive && NetworkServer.connections.Count == 0) return; Vector2 randomDirection = UnityEngine.Random.insideUnitCircle.normalized; rigidBody.angularVelocity = Vector3.zero; rigidBody.velocity = Vector3.zero;//new Vector3(randomDirection.x, 0, randomDirection.y); transform.forward = new Vector3(1, 0, 1); transform.position = startingPosition; } void OnTriggerEnter(Collider Col) { // If the ball collided with Goal1 or Goal2: if (Col.gameObject.tag == "Goal1" || Col.gameObject.tag == "Goal2") { //Gotta play the sound before resetting SoundManager.instance.PlaySingle(GetComponent<SFXBall>().goalUp); // Respawn ball at center if on the server or local // HACK moved to score to make win state work //ResetBall(); // Only handle scoring server-side of local if (NetworkManager.singleton.isNetworkActive && NetworkServer.connections.Count == 0) return; // If the ball collided with Goal1: if (Col.gameObject.tag == "Goal1") { //Debug.Log("Collided with Goal1"); // Alert other scripts that ball hit Goal1. if (OnTriggerEnterGoal1 != null) { OnTriggerEnterGoal1(); } } // Else if the ball collided with Goal2: else if (Col.gameObject.tag == "Goal2") { //Debug.Log("Collided with Goal2"); // Alert other scripts that ball hit Goal2. if (OnTriggerEnterGoal2 != null) { OnTriggerEnterGoal2(); } } // We need to add some wait time and "Goal!" message eventually. The following would not work without other changes: //yield return new WaitForSeconds(5); } else if (Col.gameObject.tag == "Lightpad") { if (OnTriggerEnterRollover != null) { OnTriggerEnterRollover(); } } } void OnCollisionExit(Collision other) { // Only handle ball force server-side of local if (NetworkManager.singleton.isNetworkActive && NetworkServer.connections.Count == 0) return; if (other.gameObject.tag == "Paddle" || other.gameObject.tag == "Bumper") { //Debug.Log ("Adding force to ball"); rigidBody.AddForce (rigidBody.velocity.normalized * collisionForceMultiplier); if (other.gameObject.tag == "Bumper") { if (OnTriggerEnterBumper != null) { OnTriggerEnterBumper(); } } } } }
namespace PhoneManagementSystem.Data.Migrations { using System; using System.Data.Entity; using System.Collections.Generic; using System.Data.Entity.Migrations; using System.Linq; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity; using PhoneManagementSystem.Models; using PhoneManagementSystem.Commons; public sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext> { private Random random = new Random(0); public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; } protected override void Seed(ApplicationDbContext context) { if (context.Users.Any()) { return; } var jobTitles = this.SeedJobTitles(context); var departments = this.SeedDepartment(context); var phones = this.SeedPhones(context); var users = this.SeedUsers(context, jobTitles, departments); this.SeedPhonesUsersOrders(context, phones, users); } private void SeedPhonesUsersOrders(ApplicationDbContext context, IList<Phone> phones, ICollection<User> users) { foreach (var user in users) { var phone = phones[this.random.Next(0, phones.Count)]; phones.Remove(phone); var order = new PhoneNumberOrder() { PhoneId = phone.PhoneId, UserId = user.Id, ActionDate = DateTime.Now, PhoneAction = PhoneAction.TakePhone, AdminId = context.Users.Where(x => x.UserName == "admin").Select(x => x.Id).FirstOrDefault() }; var newPhone = context.Phones.Where(x => x.PhoneId == phone.PhoneId).FirstOrDefault(); newPhone.PhoneStatus = PhoneStatus.Taken; context.PhoneNumberOrders.Add(order); } context.SaveChanges(); } private IList<Department> SeedDepartment(ApplicationDbContext context) { var departments = new List<Department>(); var departmentNames = new List<string> { "Gastroenterology", "Pulmology", "Dermatology" }; foreach (var departmentName in departmentNames) { var department = new Department { Name = departmentName }; context.Departments.Add(department); departments.Add(department); } context.SaveChanges(); return departments; } private IList<JobTitle> SeedJobTitles(ApplicationDbContext context) { var jobTitleNames = new string[] { "admin", "expert" }; var jobTiles = new List<JobTitle>(); foreach (var jobTitleName in jobTitleNames) { var jobTitle = new JobTitle { Name = jobTitleName }; context.JobTitles.Add(jobTitle); jobTiles.Add(jobTitle); } context.SaveChanges(); return jobTiles; } private IList<Phone> SeedPhones(ApplicationDbContext context) { var phones = new List<Phone>(); for (int i = 0; i < 20; i++) { var phone = new Phone { PhoneId = RandomPhoneNumber(), PhoneStatus = PhoneStatus.Free, CardType = CardType.Unknown, CreditLimit = 50, HasRouming = true }; if (phones.Any(x => x.PhoneId == phone.PhoneId)) { i--; continue; } phones.Add(phone); context.Phones.Add(phone); } context.SaveChanges(); return phones; } private ICollection<User> SeedUsers(ApplicationDbContext context, IList<JobTitle> jobTitles, IList<Department> departments) { var usernames = new string[] { "admin", "maria", "peter", "kiro", "didi" }; var users = new List<User>(); var userStore = new UserStore<User>(context); var userManager = new UserManager<User>(userStore); userManager.PasswordValidator = new PasswordValidator { RequiredLength = 2, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false, }; foreach (var username in usernames) { var name = username[0].ToString().ToUpper() + username.Substring(1); int i = 0; var user = new User { UserName = username, FullName = name, Email = username + "@gmail.com", EmployeeNumber = ++i, IsActive = true, Department = departments[this.random.Next(0, departments.Count())], JobTitle = jobTitles[this.random.Next(0, jobTitles.Count())] }; var password = username; var userCreateResult = userManager.Create(user, password); if (userCreateResult.Succeeded) { users.Add(user); } else { throw new Exception(string.Join("; ", userCreateResult.Errors)); } } // Create "Administrator" role var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var roleCreateResult = roleManager.Create(new IdentityRole(GlobalConstants.AdminRole)); if (!roleCreateResult.Succeeded) { throw new Exception(string.Join("; ", roleCreateResult.Errors)); } // Add "admin" user to "Administrator" role var adminUser = users.First(user => user.UserName == "admin"); adminUser.JobTitle = context.JobTitles.Where(jt => jt.Name == "admin").First(); var addAdminRoleResult = userManager.AddToRole(adminUser.Id, "Administrator"); if (!addAdminRoleResult.Succeeded) { throw new Exception(string.Join("; ", addAdminRoleResult.Errors)); } context.SaveChanges(); return users; } private string RandomPhoneNumber() { var middleNumber = new int[] { 993, 933 }; return "0884" + middleNumber[random.Next(0, middleNumber.Length)] + random.Next(0, 1000).ToString().PadLeft(3, '0'); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Logging; using osu.Game.Database; using osu.Game.Online.API; using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.Rooms; using osu.Game.Online.Rooms.RoomStatuses; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Utils; using APIUser = osu.Game.Online.API.Requests.Responses.APIUser; namespace osu.Game.Online.Multiplayer { public abstract class MultiplayerClient : Component, IMultiplayerClient, IMultiplayerRoomServer { /// <summary> /// Invoked when any change occurs to the multiplayer room. /// </summary> public event Action? RoomUpdated; /// <summary> /// Invoked when a new user joins the room. /// </summary> public event Action<MultiplayerRoomUser>? UserJoined; /// <summary> /// Invoked when a user leaves the room of their own accord. /// </summary> public event Action<MultiplayerRoomUser>? UserLeft; /// <summary> /// Invoked when a user was kicked from the room forcefully. /// </summary> public event Action<MultiplayerRoomUser>? UserKicked; /// <summary> /// Invoked when a new item is added to the playlist. /// </summary> public event Action<MultiplayerPlaylistItem>? ItemAdded; /// <summary> /// Invoked when a playlist item is removed from the playlist. The provided <c>long</c> is the playlist's item ID. /// </summary> public event Action<long>? ItemRemoved; /// <summary> /// Invoked when a playlist item's details change. /// </summary> public event Action<MultiplayerPlaylistItem>? ItemChanged; /// <summary> /// Invoked when the multiplayer server requests the current beatmap to be loaded into play. /// </summary> public event Action? LoadRequested; /// <summary> /// Invoked when the multiplayer server requests gameplay to be started. /// </summary> public event Action? MatchStarted; /// <summary> /// Invoked when the multiplayer server has finished collating results. /// </summary> public event Action? ResultsReady; /// <summary> /// Whether the <see cref="MultiplayerClient"/> is currently connected. /// This is NOT thread safe and usage should be scheduled. /// </summary> public abstract IBindable<bool> IsConnected { get; } /// <summary> /// The joined <see cref="MultiplayerRoom"/>. /// </summary> public MultiplayerRoom? Room { get; private set; } /// <summary> /// The users in the joined <see cref="Room"/> which are participating in the current gameplay loop. /// </summary> public IBindableList<int> CurrentMatchPlayingUserIds => PlayingUserIds; protected readonly BindableList<int> PlayingUserIds = new BindableList<int>(); /// <summary> /// The <see cref="MultiplayerRoomUser"/> corresponding to the local player, if available. /// </summary> public MultiplayerRoomUser? LocalUser => Room?.Users.SingleOrDefault(u => u.User?.Id == API.LocalUser.Value.Id); /// <summary> /// Whether the <see cref="LocalUser"/> is the host in <see cref="Room"/>. /// </summary> public bool IsHost { get { var localUser = LocalUser; return localUser != null && Room?.Host != null && localUser.Equals(Room.Host); } } [Resolved] protected IAPIProvider API { get; private set; } = null!; [Resolved] protected IRulesetStore Rulesets { get; private set; } = null!; [Resolved] private UserLookupCache userLookupCache { get; set; } = null!; protected Room? APIRoom { get; private set; } [BackgroundDependencyLoader] private void load() { IsConnected.BindValueChanged(connected => { // clean up local room state on server disconnect. if (!connected.NewValue && Room != null) { Logger.Log("Connection to multiplayer server was lost.", LoggingTarget.Runtime, LogLevel.Important); LeaveRoom(); } }); } private readonly TaskChain joinOrLeaveTaskChain = new TaskChain(); private CancellationTokenSource? joinCancellationSource; /// <summary> /// Joins the <see cref="MultiplayerRoom"/> for a given API <see cref="Room"/>. /// </summary> /// <param name="room">The API <see cref="Room"/>.</param> /// <param name="password">An optional password to use for the join operation.</param> public async Task JoinRoom(Room room, string? password = null) { var cancellationSource = joinCancellationSource = new CancellationTokenSource(); await joinOrLeaveTaskChain.Add(async () => { if (Room != null) throw new InvalidOperationException("Cannot join a multiplayer room while already in one."); Debug.Assert(room.RoomID.Value != null); // Join the server-side room. var joinedRoom = await JoinRoom(room.RoomID.Value.Value, password ?? room.Password.Value).ConfigureAwait(false); Debug.Assert(joinedRoom != null); // Populate users. Debug.Assert(joinedRoom.Users != null); await Task.WhenAll(joinedRoom.Users.Select(PopulateUser)).ConfigureAwait(false); // Update the stored room (must be done on update thread for thread-safety). await scheduleAsync(() => { Room = joinedRoom; APIRoom = room; APIRoom.Playlist.Clear(); APIRoom.Playlist.AddRange(joinedRoom.Playlist.Select(createPlaylistItem)); Debug.Assert(LocalUser != null); addUserToAPIRoom(LocalUser); foreach (var user in joinedRoom.Users) updateUserPlayingState(user.UserID, user.State); updateLocalRoomSettings(joinedRoom.Settings); OnRoomJoined(); }, cancellationSource.Token).ConfigureAwait(false); }, cancellationSource.Token).ConfigureAwait(false); } /// <summary> /// Fired when the room join sequence is complete /// </summary> protected virtual void OnRoomJoined() { } /// <summary> /// Joins the <see cref="MultiplayerRoom"/> with a given ID. /// </summary> /// <param name="roomId">The room ID.</param> /// <param name="password">An optional password to use when joining the room.</param> /// <returns>The joined <see cref="MultiplayerRoom"/>.</returns> protected abstract Task<MultiplayerRoom> JoinRoom(long roomId, string? password = null); public Task LeaveRoom() { // The join may have not completed yet, so certain tasks that either update the room or reference the room should be cancelled. // This includes the setting of Room itself along with the initial update of the room settings on join. joinCancellationSource?.Cancel(); // Leaving rooms is expected to occur instantaneously whilst the operation is finalised in the background. // However a few members need to be reset immediately to prevent other components from entering invalid states whilst the operation hasn't yet completed. // For example, if a room was left and the user immediately pressed the "create room" button, then the user could be taken into the lobby if the value of Room is not reset in time. var scheduledReset = scheduleAsync(() => { APIRoom = null; Room = null; PlayingUserIds.Clear(); RoomUpdated?.Invoke(); }); return joinOrLeaveTaskChain.Add(async () => { await scheduledReset.ConfigureAwait(false); await LeaveRoomInternal().ConfigureAwait(false); }); } protected abstract Task LeaveRoomInternal(); /// <summary> /// Change the current <see cref="MultiplayerRoom"/> settings. /// </summary> /// <remarks> /// A room must be joined for this to have any effect. /// </remarks> /// <param name="name">The new room name, if any.</param> /// <param name="password">The new password, if any.</param> /// <param name="matchType">The type of the match, if any.</param> /// <param name="queueMode">The new queue mode, if any.</param> public Task ChangeSettings(Optional<string> name = default, Optional<string> password = default, Optional<MatchType> matchType = default, Optional<QueueMode> queueMode = default) { if (Room == null) throw new InvalidOperationException("Must be joined to a match to change settings."); return ChangeSettings(new MultiplayerRoomSettings { Name = name.GetOr(Room.Settings.Name), Password = password.GetOr(Room.Settings.Password), MatchType = matchType.GetOr(Room.Settings.MatchType), QueueMode = queueMode.GetOr(Room.Settings.QueueMode), }); } /// <summary> /// Toggles the <see cref="LocalUser"/>'s ready state. /// </summary> /// <exception cref="InvalidOperationException">If a toggle of ready state is not valid at this time.</exception> public async Task ToggleReady() { var localUser = LocalUser; if (localUser == null) return; switch (localUser.State) { case MultiplayerUserState.Idle: await ChangeState(MultiplayerUserState.Ready).ConfigureAwait(false); return; case MultiplayerUserState.Ready: await ChangeState(MultiplayerUserState.Idle).ConfigureAwait(false); return; default: throw new InvalidOperationException($"Cannot toggle ready when in {localUser.State}"); } } /// <summary> /// Toggles the <see cref="LocalUser"/>'s spectating state. /// </summary> /// <exception cref="InvalidOperationException">If a toggle of the spectating state is not valid at this time.</exception> public async Task ToggleSpectate() { var localUser = LocalUser; if (localUser == null) return; switch (localUser.State) { case MultiplayerUserState.Idle: case MultiplayerUserState.Ready: await ChangeState(MultiplayerUserState.Spectating).ConfigureAwait(false); return; case MultiplayerUserState.Spectating: await ChangeState(MultiplayerUserState.Idle).ConfigureAwait(false); return; default: throw new InvalidOperationException($"Cannot toggle spectate when in {localUser.State}"); } } public abstract Task TransferHost(int userId); public abstract Task KickUser(int userId); public abstract Task ChangeSettings(MultiplayerRoomSettings settings); public abstract Task ChangeState(MultiplayerUserState newState); public abstract Task ChangeBeatmapAvailability(BeatmapAvailability newBeatmapAvailability); /// <summary> /// Change the local user's mods in the currently joined room. /// </summary> /// <param name="newMods">The proposed new mods, excluding any required by the room itself.</param> public Task ChangeUserMods(IEnumerable<Mod> newMods) => ChangeUserMods(newMods.Select(m => new APIMod(m)).ToList()); public abstract Task ChangeUserMods(IEnumerable<APIMod> newMods); public abstract Task SendMatchRequest(MatchUserRequest request); public abstract Task StartMatch(); public abstract Task AbortGameplay(); public abstract Task AddPlaylistItem(MultiplayerPlaylistItem item); public abstract Task EditPlaylistItem(MultiplayerPlaylistItem item); public abstract Task RemovePlaylistItem(long playlistItemId); Task IMultiplayerClient.RoomStateChanged(MultiplayerRoomState state) { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { if (Room == null) return; Debug.Assert(APIRoom != null); Room.State = state; switch (state) { case MultiplayerRoomState.Open: APIRoom.Status.Value = new RoomStatusOpen(); break; case MultiplayerRoomState.Playing: APIRoom.Status.Value = new RoomStatusPlaying(); break; case MultiplayerRoomState.Closed: APIRoom.Status.Value = new RoomStatusEnded(); break; } RoomUpdated?.Invoke(); }, false); return Task.CompletedTask; } async Task IMultiplayerClient.UserJoined(MultiplayerRoomUser user) { if (Room == null) return; await PopulateUser(user).ConfigureAwait(false); Scheduler.Add(() => { if (Room == null) return; // for sanity, ensure that there can be no duplicate users in the room user list. if (Room.Users.Any(existing => existing.UserID == user.UserID)) return; Room.Users.Add(user); addUserToAPIRoom(user); UserJoined?.Invoke(user); RoomUpdated?.Invoke(); }); } Task IMultiplayerClient.UserLeft(MultiplayerRoomUser user) => handleUserLeft(user, UserLeft); Task IMultiplayerClient.UserKicked(MultiplayerRoomUser user) { if (LocalUser == null) return Task.CompletedTask; if (user.Equals(LocalUser)) LeaveRoom(); return handleUserLeft(user, UserKicked); } private void addUserToAPIRoom(MultiplayerRoomUser user) { Debug.Assert(APIRoom != null); APIRoom.RecentParticipants.Add(user.User ?? new APIUser { Id = user.UserID, Username = "[Unresolved]" }); APIRoom.ParticipantCount.Value++; } private Task handleUserLeft(MultiplayerRoomUser user, Action<MultiplayerRoomUser>? callback) { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { if (Room == null) return; Room.Users.Remove(user); PlayingUserIds.Remove(user.UserID); Debug.Assert(APIRoom != null); APIRoom.RecentParticipants.RemoveAll(u => u.Id == user.UserID); APIRoom.ParticipantCount.Value--; callback?.Invoke(user); RoomUpdated?.Invoke(); }, false); return Task.CompletedTask; } Task IMultiplayerClient.HostChanged(int userId) { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { if (Room == null) return; Debug.Assert(APIRoom != null); var user = Room.Users.FirstOrDefault(u => u.UserID == userId); Room.Host = user; APIRoom.Host.Value = user?.User; RoomUpdated?.Invoke(); }, false); return Task.CompletedTask; } Task IMultiplayerClient.SettingsChanged(MultiplayerRoomSettings newSettings) { Debug.Assert(APIRoom != null); Debug.Assert(Room != null); Scheduler.Add(() => updateLocalRoomSettings(newSettings)); return Task.CompletedTask; } Task IMultiplayerClient.UserStateChanged(int userId, MultiplayerUserState state) { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { if (Room == null) return; Room.Users.Single(u => u.UserID == userId).State = state; updateUserPlayingState(userId, state); RoomUpdated?.Invoke(); }, false); return Task.CompletedTask; } Task IMultiplayerClient.MatchUserStateChanged(int userId, MatchUserState state) { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { if (Room == null) return; Room.Users.Single(u => u.UserID == userId).MatchState = state; RoomUpdated?.Invoke(); }, false); return Task.CompletedTask; } Task IMultiplayerClient.MatchRoomStateChanged(MatchRoomState state) { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { if (Room == null) return; Room.MatchState = state; RoomUpdated?.Invoke(); }, false); return Task.CompletedTask; } public Task MatchEvent(MatchServerEvent e) { // not used by any match types just yet. return Task.CompletedTask; } Task IMultiplayerClient.UserBeatmapAvailabilityChanged(int userId, BeatmapAvailability beatmapAvailability) { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { var user = Room?.Users.SingleOrDefault(u => u.UserID == userId); // errors here are not critical - beatmap availability state is mostly for display. if (user == null) return; user.BeatmapAvailability = beatmapAvailability; RoomUpdated?.Invoke(); }, false); return Task.CompletedTask; } public Task UserModsChanged(int userId, IEnumerable<APIMod> mods) { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { var user = Room?.Users.SingleOrDefault(u => u.UserID == userId); // errors here are not critical - user mods are mostly for display. if (user == null) return; user.Mods = mods; RoomUpdated?.Invoke(); }, false); return Task.CompletedTask; } Task IMultiplayerClient.LoadRequested() { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { if (Room == null) return; LoadRequested?.Invoke(); }, false); return Task.CompletedTask; } Task IMultiplayerClient.MatchStarted() { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { if (Room == null) return; MatchStarted?.Invoke(); }, false); return Task.CompletedTask; } Task IMultiplayerClient.ResultsReady() { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { if (Room == null) return; ResultsReady?.Invoke(); }, false); return Task.CompletedTask; } public Task PlaylistItemAdded(MultiplayerPlaylistItem item) { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { if (Room == null) return; Debug.Assert(APIRoom != null); Room.Playlist.Add(item); APIRoom.Playlist.Add(createPlaylistItem(item)); ItemAdded?.Invoke(item); RoomUpdated?.Invoke(); }); return Task.CompletedTask; } public Task PlaylistItemRemoved(long playlistItemId) { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { if (Room == null) return; Debug.Assert(APIRoom != null); Room.Playlist.Remove(Room.Playlist.Single(existing => existing.ID == playlistItemId)); APIRoom.Playlist.RemoveAll(existing => existing.ID == playlistItemId); ItemRemoved?.Invoke(playlistItemId); RoomUpdated?.Invoke(); }); return Task.CompletedTask; } public Task PlaylistItemChanged(MultiplayerPlaylistItem item) { if (Room == null) return Task.CompletedTask; Scheduler.Add(() => { if (Room == null) return; Debug.Assert(APIRoom != null); Room.Playlist[Room.Playlist.IndexOf(Room.Playlist.Single(existing => existing.ID == item.ID))] = item; int existingIndex = APIRoom.Playlist.IndexOf(APIRoom.Playlist.Single(existing => existing.ID == item.ID)); APIRoom.Playlist.RemoveAt(existingIndex); APIRoom.Playlist.Insert(existingIndex, createPlaylistItem(item)); ItemChanged?.Invoke(item); RoomUpdated?.Invoke(); }); return Task.CompletedTask; } /// <summary> /// Populates the <see cref="APIUser"/> for a given <see cref="MultiplayerRoomUser"/>. /// </summary> /// <param name="multiplayerUser">The <see cref="MultiplayerRoomUser"/> to populate.</param> protected async Task PopulateUser(MultiplayerRoomUser multiplayerUser) => multiplayerUser.User ??= await userLookupCache.GetUserAsync(multiplayerUser.UserID).ConfigureAwait(false); /// <summary> /// Updates the local room settings with the given <see cref="MultiplayerRoomSettings"/>. /// </summary> /// <remarks> /// This updates both the joined <see cref="MultiplayerRoom"/> and the respective API <see cref="Room"/>. /// </remarks> /// <param name="settings">The new <see cref="MultiplayerRoomSettings"/> to update from.</param> private void updateLocalRoomSettings(MultiplayerRoomSettings settings) { if (Room == null) return; Debug.Assert(APIRoom != null); // Update a few properties of the room instantaneously. Room.Settings = settings; APIRoom.Name.Value = Room.Settings.Name; APIRoom.Password.Value = Room.Settings.Password; APIRoom.Type.Value = Room.Settings.MatchType; APIRoom.QueueMode.Value = Room.Settings.QueueMode; RoomUpdated?.Invoke(); } private PlaylistItem createPlaylistItem(MultiplayerPlaylistItem item) => new PlaylistItem(new APIBeatmap { OnlineID = item.BeatmapID }) { ID = item.ID, OwnerID = item.OwnerID, RulesetID = item.RulesetID, Expired = item.Expired, PlaylistOrder = item.PlaylistOrder, PlayedAt = item.PlayedAt, RequiredMods = item.RequiredMods.ToArray(), AllowedMods = item.AllowedMods.ToArray() }; /// <summary> /// For the provided user ID, update whether the user is included in <see cref="CurrentMatchPlayingUserIds"/>. /// </summary> /// <param name="userId">The user's ID.</param> /// <param name="state">The new state of the user.</param> private void updateUserPlayingState(int userId, MultiplayerUserState state) { bool wasPlaying = PlayingUserIds.Contains(userId); bool isPlaying = state >= MultiplayerUserState.WaitingForLoad && state <= MultiplayerUserState.FinishedPlay; if (isPlaying == wasPlaying) return; if (isPlaying) PlayingUserIds.Add(userId); else PlayingUserIds.Remove(userId); } private Task scheduleAsync(Action action, CancellationToken cancellationToken = default) { var tcs = new TaskCompletionSource<bool>(); Scheduler.Add(() => { if (cancellationToken.IsCancellationRequested) { tcs.SetCanceled(); return; } try { action(); tcs.SetResult(true); } catch (Exception ex) { tcs.SetException(ex); } }); return tcs.Task; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Roslyn.Utilities; using System.Reflection; namespace Microsoft.CodeAnalysis.Scripting { using TypeInfo = System.Reflection.TypeInfo; public abstract partial class ObjectFormatter { // internal for testing internal sealed class Formatter { private readonly ObjectFormatter _language; private readonly ObjectFormattingOptions _options; private HashSet<object> _lazyVisitedObjects; private HashSet<object> VisitedObjects { get { if (_lazyVisitedObjects == null) { _lazyVisitedObjects = new HashSet<object>(ReferenceEqualityComparer.Instance); } return _lazyVisitedObjects; } } public Formatter(ObjectFormatter language, ObjectFormattingOptions options) { _options = options ?? ObjectFormattingOptions.Default; _language = language; } private Builder MakeMemberBuilder(int limit) { return new Builder(Math.Min(_options.MaxLineLength, limit), _options, insertEllipsis: false); } public string FormatObject(object obj) { try { var builder = new Builder(_options.MaxOutputLength, _options, insertEllipsis: true); string _; return FormatObjectRecursive(builder, obj, _options.QuoteStrings, _options.MemberFormat, out _).ToString(); } catch (InsufficientExecutionStackException) { return ScriptingResources.StackOverflowWhileEvaluating; } } private Builder FormatObjectRecursive(Builder result, object obj, bool quoteStrings, MemberDisplayFormat memberFormat, out string name) { name = null; string primitive = _language.FormatPrimitive(obj, quoteStrings, _options.IncludeCodePoints, _options.UseHexadecimalNumbers); if (primitive != null) { result.Append(primitive); return result; } object originalObj = obj; TypeInfo originalType = originalObj.GetType().GetTypeInfo(); // // Override KeyValuePair<,>.ToString() to get better dictionary elements formatting: // // { { format(key), format(value) }, ... } // instead of // { [key.ToString(), value.ToString()], ... } // // This is more general than overriding Dictionary<,> debugger proxy attribute since it applies on all // types that return an array of KeyValuePair in their DebuggerDisplay to display items. // if (originalType.IsGenericType && originalType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) { if (memberFormat != MemberDisplayFormat.InlineValue) { result.Append(_language.FormatTypeName(originalType.AsType(), _options)); result.Append(' '); } FormatKeyValuePair(result, originalObj); return result; } if (originalType.IsArray) { if (!VisitedObjects.Add(originalObj)) { result.AppendInfiniteRecursionMarker(); return result; } FormatArray(result, (Array)originalObj, inline: memberFormat != MemberDisplayFormat.List); VisitedObjects.Remove(originalObj); return result; } DebuggerDisplayAttribute debuggerDisplay = GetApplicableDebuggerDisplayAttribute(originalType); if (debuggerDisplay != null) { name = debuggerDisplay.Name; } bool suppressMembers = false; // // TypeName(count) for ICollection implementers // or // TypeName([[DebuggerDisplay.Value]]) // Inline // [[DebuggerDisplay.Value]] // InlineValue // or // [[ToString()]] if ToString overridden // or // TypeName // ICollection collection; if ((collection = originalObj as ICollection) != null) { FormatCollectionHeader(result, collection); } else if (debuggerDisplay != null && !String.IsNullOrEmpty(debuggerDisplay.Value)) { if (memberFormat != MemberDisplayFormat.InlineValue) { result.Append(_language.FormatTypeName(originalType.AsType(), _options)); result.Append('('); } FormatWithEmbeddedExpressions(result, debuggerDisplay.Value, originalObj); if (memberFormat != MemberDisplayFormat.InlineValue) { result.Append(')'); } suppressMembers = true; } else if (HasOverriddenToString(originalType)) { ObjectToString(result, originalObj); suppressMembers = true; } else { result.Append(_language.FormatTypeName(originalType.AsType(), _options)); } if (memberFormat == MemberDisplayFormat.NoMembers) { return result; } bool includeNonPublic = memberFormat == MemberDisplayFormat.List; object proxy = GetDebuggerTypeProxy(obj); if (proxy != null) { obj = proxy; includeNonPublic = false; suppressMembers = false; } if (memberFormat != MemberDisplayFormat.List && suppressMembers) { return result; } // TODO (tomat): we should not use recursion RuntimeHelpers.EnsureSufficientExecutionStack(); result.Append(' '); if (!VisitedObjects.Add(originalObj)) { result.AppendInfiniteRecursionMarker(); return result; } // handle special types only if a proxy isn't defined if (proxy == null) { IDictionary dictionary; if ((dictionary = obj as IDictionary) != null) { FormatDictionary(result, dictionary, inline: memberFormat != MemberDisplayFormat.List); return result; } IEnumerable enumerable; if ((enumerable = obj as IEnumerable) != null) { FormatSequence(result, enumerable, inline: memberFormat != MemberDisplayFormat.List); return result; } } FormatObjectMembers(result, obj, originalType, includeNonPublic, inline: memberFormat != MemberDisplayFormat.List); VisitedObjects.Remove(obj); return result; } #region Members /// <summary> /// Formats object members to a list. /// /// Inline == false: /// <code> /// { A=true, B=false, C=new int[3] { 1, 2, 3 } } /// </code> /// /// Inline == true: /// <code> /// { /// A: true, /// B: false, /// C: new int[3] { 1, 2, 3 } /// } /// </code> /// </summary> private void FormatObjectMembers(Builder result, object obj, TypeInfo originalType, bool includeNonPublic, bool inline) { int lengthLimit = result.Remaining; if (lengthLimit < 0) { return; } var members = new List<FormattedMember>(); // Limits the number of members added into the result. Some more members may be added than it will fit into the result // and will be thrown away later but not many more. FormatObjectMembersRecursive(members, obj, includeNonPublic, ref lengthLimit); bool useCollectionFormat = UseCollectionFormat(members, originalType); result.AppendGroupOpening(); for (int i = 0; i < members.Count; i++) { result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline); if (useCollectionFormat) { members[i].AppendAsCollectionEntry(result); } else { members[i].Append(result, inline ? "=" : ": "); } if (result.LimitReached) { break; } } result.AppendGroupClosing(inline); } private static bool UseCollectionFormat(IEnumerable<FormattedMember> members, TypeInfo originalType) { return typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(originalType) && members.All(member => member.Index >= 0); } private struct FormattedMember { // Non-negative if the member is an inlined element of an array (DebuggerBrowsableState.RootHidden applied on a member of array type). public readonly int Index; // Formatted name of the member or null if it doesn't have a name (Index is >=0 then). public readonly string Name; // Formatted value of the member. public readonly string Value; public FormattedMember(int index, string name, string value) { Name = name; Index = index; Value = value; } public int MinimalLength { get { return (Name != null ? Name.Length : "[0]".Length) + Value.Length; } } public string GetDisplayName() { return Name ?? "[" + Index.ToString() + "]"; } public bool HasKeyName() { return Index >= 0 && Name != null && Name.Length >= 2 && Name[0] == '[' && Name[Name.Length - 1] == ']'; } public bool AppendAsCollectionEntry(Builder result) { // Some BCL collections use [{key.ToString()}]: {value.ToString()} pattern to display collection entries. // We want them to be printed initializer-style, i.e. { <key>, <value> } if (HasKeyName()) { result.AppendGroupOpening(); result.AppendCollectionItemSeparator(isFirst: true, inline: true); result.Append(Name, 1, Name.Length - 2); result.AppendCollectionItemSeparator(isFirst: false, inline: true); result.Append(Value); result.AppendGroupClosing(inline: true); } else { result.Append(Value); } return true; } public bool Append(Builder result, string separator) { result.Append(GetDisplayName()); result.Append(separator); result.Append(Value); return true; } } /// <summary> /// Enumerates sorted object members to display. /// </summary> private void FormatObjectMembersRecursive(List<FormattedMember> result, object obj, bool includeNonPublic, ref int lengthLimit) { Debug.Assert(obj != null); var members = new List<MemberInfo>(); var type = obj.GetType().GetTypeInfo(); while (type != null) { members.AddRange(type.DeclaredFields.Where(f => !f.IsStatic)); members.AddRange(type.DeclaredProperties.Where(f => f.GetMethod != null && !f.GetMethod.IsStatic)); type = type.BaseType?.GetTypeInfo(); } members.Sort((x, y) => { // Need case-sensitive comparison here so that the order of members is // always well-defined (members can differ by case only). And we don't want to // depend on that order. int comparisonResult = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name); if (comparisonResult == 0) { comparisonResult = StringComparer.Ordinal.Compare(x.Name, y.Name); } return comparisonResult; }); foreach (var member in members) { if (_language.IsHiddenMember(member)) { continue; } bool rootHidden = false, ignoreVisibility = false; var browsable = (DebuggerBrowsableAttribute)member.GetCustomAttributes(typeof(DebuggerBrowsableAttribute), false).FirstOrDefault(); if (browsable != null) { if (browsable.State == DebuggerBrowsableState.Never) { continue; } ignoreVisibility = true; rootHidden = browsable.State == DebuggerBrowsableState.RootHidden; } FieldInfo field = member as FieldInfo; if (field != null) { if (!(includeNonPublic || ignoreVisibility || field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly)) { continue; } } else { PropertyInfo property = (PropertyInfo)member; var getter = property.GetMethod; if (getter == null) { continue; } var setter = property.SetMethod; // If not ignoring visibility include properties that has a visible getter or setter. if (!(includeNonPublic || ignoreVisibility || getter.IsPublic || getter.IsFamily || getter.IsFamilyOrAssembly || (setter != null && (setter.IsPublic || setter.IsFamily || setter.IsFamilyOrAssembly)))) { continue; } if (getter.GetParameters().Length > 0) { continue; } } var debuggerDisplay = GetApplicableDebuggerDisplayAttribute(member); if (debuggerDisplay != null) { string k = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Name, obj) ?? _language.FormatMemberName(member); string v = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Value, obj) ?? string.Empty; // TODO: ? if (!AddMember(result, new FormattedMember(-1, k, v), ref lengthLimit)) { return; } continue; } Exception exception; object value = GetMemberValue(member, obj, out exception); if (exception != null) { var memberValueBuilder = MakeMemberBuilder(lengthLimit); FormatException(memberValueBuilder, exception); if (!AddMember(result, new FormattedMember(-1, _language.FormatMemberName(member), memberValueBuilder.ToString()), ref lengthLimit)) { return; } continue; } if (rootHidden) { if (value != null && !VisitedObjects.Contains(value)) { Array array; if ((array = value as Array) != null) // TODO (tomat): n-dim arrays { int i = 0; foreach (object item in array) { string name; Builder valueBuilder = MakeMemberBuilder(lengthLimit); FormatObjectRecursive(valueBuilder, item, _options.QuoteStrings, MemberDisplayFormat.InlineValue, out name); if (!string.IsNullOrEmpty(name)) { name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, item).ToString(); } if (!AddMember(result, new FormattedMember(i, name, valueBuilder.ToString()), ref lengthLimit)) { return; } i++; } } else if (_language.FormatPrimitive(value, _options.QuoteStrings, _options.IncludeCodePoints, _options.UseHexadecimalNumbers) == null && VisitedObjects.Add(value)) { FormatObjectMembersRecursive(result, value, includeNonPublic, ref lengthLimit); VisitedObjects.Remove(value); } } } else { string name; Builder valueBuilder = MakeMemberBuilder(lengthLimit); FormatObjectRecursive(valueBuilder, value, _options.QuoteStrings, MemberDisplayFormat.InlineValue, out name); if (String.IsNullOrEmpty(name)) { name = _language.FormatMemberName(member); } else { name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, value).ToString(); } if (!AddMember(result, new FormattedMember(-1, name, valueBuilder.ToString()), ref lengthLimit)) { return; } } } } private bool AddMember(List<FormattedMember> members, FormattedMember member, ref int remainingLength) { // Add this item even if we exceed the limit - its prefix might be appended to the result. members.Add(member); // We don't need to calculate an exact length, just a lower bound on the size. // We can add more members to the result than it will eventually fit, we shouldn't add less. // Add 2 more, even if only one or half of it fit, so that the separator is included in edge cases. if (remainingLength == int.MinValue) { return false; } remainingLength -= member.MinimalLength; if (remainingLength <= 0) { remainingLength = int.MinValue; } return true; } private void FormatException(Builder result, Exception exception) { result.Append("!<"); result.Append(_language.FormatTypeName(exception.GetType(), _options)); result.Append('>'); } #endregion #region Collections private void FormatKeyValuePair(Builder result, object obj) { TypeInfo type = obj.GetType().GetTypeInfo(); object key = type.GetDeclaredProperty("Key").GetValue(obj, SpecializedCollections.EmptyObjects); object value = type.GetDeclaredProperty("Value").GetValue(obj, SpecializedCollections.EmptyObjects); string _; result.AppendGroupOpening(); result.AppendCollectionItemSeparator(isFirst: true, inline: true); FormatObjectRecursive(result, key, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out _); result.AppendCollectionItemSeparator(isFirst: false, inline: true); FormatObjectRecursive(result, value, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out _); result.AppendGroupClosing(inline: true); } private void FormatCollectionHeader(Builder result, ICollection collection) { Array array = collection as Array; if (array != null) { result.Append(_language.FormatArrayTypeName(array.GetType(), array, _options)); return; } result.Append(_language.FormatTypeName(collection.GetType(), _options)); try { result.Append('('); result.Append(collection.Count.ToString()); result.Append(')'); } catch (Exception) { // skip } } private void FormatArray(Builder result, Array array, bool inline) { FormatCollectionHeader(result, array); if (array.Rank > 1) { FormatMultidimensionalArray(result, array, inline); } else { result.Append(' '); FormatSequence(result, (IEnumerable)array, inline); } } private void FormatDictionary(Builder result, IDictionary dict, bool inline) { result.AppendGroupOpening(); int i = 0; try { IDictionaryEnumerator enumerator = dict.GetEnumerator(); IDisposable disposable = enumerator as IDisposable; try { while (enumerator.MoveNext()) { var entry = enumerator.Entry; string _; result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline); result.AppendGroupOpening(); result.AppendCollectionItemSeparator(isFirst: true, inline: true); FormatObjectRecursive(result, entry.Key, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out _); result.AppendCollectionItemSeparator(isFirst: false, inline: true); FormatObjectRecursive(result, entry.Value, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out _); result.AppendGroupClosing(inline: true); i++; } } finally { if (disposable != null) { disposable.Dispose(); } } } catch (Exception e) { result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline); FormatException(result, e); result.Append(' '); result.Append(_options.Ellipsis); } result.AppendGroupClosing(inline); } private void FormatSequence(Builder result, IEnumerable sequence, bool inline) { result.AppendGroupOpening(); int i = 0; try { foreach (var item in sequence) { string name; result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline); FormatObjectRecursive(result, item, quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out name); i++; } } catch (Exception e) { result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline); FormatException(result, e); result.Append(" ..."); } result.AppendGroupClosing(inline); } private void FormatMultidimensionalArray(Builder result, Array array, bool inline) { Debug.Assert(array.Rank > 1); if (array.Length == 0) { result.AppendCollectionItemSeparator(isFirst: true, inline: true); result.AppendGroupOpening(); result.AppendGroupClosing(inline: true); return; } int[] indices = new int[array.Rank]; for (int i = array.Rank - 1; i >= 0; i--) { indices[i] = array.GetLowerBound(i); } int nesting = 0; int flatIndex = 0; while (true) { // increment indices (lower index overflows to higher): int i = indices.Length - 1; while (indices[i] > array.GetUpperBound(i)) { indices[i] = array.GetLowerBound(i); result.AppendGroupClosing(inline: inline || nesting != 1); nesting--; i--; if (i < 0) { return; } indices[i]++; } result.AppendCollectionItemSeparator(isFirst: flatIndex == 0, inline: inline || nesting != 1); i = indices.Length - 1; while (i >= 0 && indices[i] == array.GetLowerBound(i)) { result.AppendGroupOpening(); nesting++; // array isn't empty, so there is always an element following this separator result.AppendCollectionItemSeparator(isFirst: true, inline: inline || nesting != 1); i--; } string name; FormatObjectRecursive(result, array.GetValue(indices), quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out name); indices[indices.Length - 1]++; flatIndex++; } } #endregion #region Scalars private void ObjectToString(Builder result, object obj) { try { string str = obj.ToString(); result.Append('['); result.Append(str); result.Append(']'); } catch (Exception e) { FormatException(result, e); } } #endregion #region DebuggerDisplay Embedded Expressions /// <summary> /// Evaluate a format string with possible member references enclosed in braces. /// E.g. "foo = {GetFooString(),nq}, bar = {Bar}". /// </summary> /// <remarks> /// Although in theory any expression is allowed to be embedded in the string such behavior is in practice fundamentally broken. /// The attribute doesn't specify what language (VB, C#, F#, etc.) to use to parse these expressions. Even if it did all languages /// would need to be able to evaluate each other language's expressions, which is not viable and the Expression Evaluator doesn't /// work that way today. Instead it evaluates the embedded expressions in the language of the current method frame. When consuming /// VB objects from C#, for example, the evaluation might fail due to language mismatch (evaluating VB expression using C# parser). /// /// Therefore we limit the expressions to a simple language independent syntax: {clr-member-name} '(' ')' ',nq', /// where parentheses and ,nq suffix (no-quotes) are optional and the name is an arbitrary CLR field, property, or method name. /// We then resolve the member by name using case-sensitive lookup first with fallback to case insensitive and evaluate it. /// If parentheses are present we only look for methods. /// Only parameter less members are considered. /// </remarks> private string FormatWithEmbeddedExpressions(int lengthLimit, string format, object obj) { if (String.IsNullOrEmpty(format)) { return null; } return FormatWithEmbeddedExpressions(new Builder(lengthLimit, _options, insertEllipsis: false), format, obj).ToString(); } private Builder FormatWithEmbeddedExpressions(Builder result, string format, object obj) { int i = 0; while (i < format.Length) { char c = format[i++]; if (c == '{') { if (i >= 2 && format[i - 2] == '\\') { result.Append('{'); } else { int expressionEnd = format.IndexOf('}', i); bool noQuotes, callableOnly; string memberName; if (expressionEnd == -1 || (memberName = ParseSimpleMemberName(format, i, expressionEnd, out noQuotes, out callableOnly)) == null) { // the expression isn't properly formatted result.Append(format, i - 1, format.Length - i + 1); break; } MemberInfo member = ResolveMember(obj, memberName, callableOnly); if (member == null) { result.AppendFormat(callableOnly ? "!<Method '{0}' not found>" : "!<Member '{0}' not found>", memberName); } else { Exception exception; object value = GetMemberValue(member, obj, out exception); if (exception != null) { FormatException(result, exception); } else { string name; FormatObjectRecursive(result, value, !noQuotes, MemberDisplayFormat.NoMembers, out name); } } i = expressionEnd + 1; } } else { result.Append(c); } } return result; } // Parses // <clr-member-name> // <clr-member-name> ',' 'nq' // <clr-member-name> '(' ')' // <clr-member-name> '(' ')' ',' 'nq' // // Internal for testing purposes. internal static string ParseSimpleMemberName(string str, int start, int end, out bool noQuotes, out bool isCallable) { Debug.Assert(str != null && start >= 0 && end >= start); isCallable = false; noQuotes = false; // no-quotes suffix: if (end - 3 >= start && str[end - 2] == 'n' && str[end - 1] == 'q') { int j = end - 3; while (j >= start && Char.IsWhiteSpace(str[j])) { j--; } if (j >= start && str[j] == ',') { noQuotes = true; end = j; } } int i = end - 1; EatTrailingWhiteSpace(str, start, ref i); if (i > start && str[i] == ')') { int closingParen = i; i--; EatTrailingWhiteSpace(str, start, ref i); if (str[i] != '(') { i = closingParen; } else { i--; EatTrailingWhiteSpace(str, start, ref i); isCallable = true; } } EatLeadingWhiteSpace(str, ref start, i); return str.Substring(start, i - start + 1); } private static void EatTrailingWhiteSpace(string str, int start, ref int i) { while (i >= start && Char.IsWhiteSpace(str[i])) { i--; } } private static void EatLeadingWhiteSpace(string str, ref int i, int end) { while (i < end && Char.IsWhiteSpace(str[i])) { i++; } } #endregion } } }
//------------------------------------------------------------------------------ // <copyright file="PersonalizationStateInfoCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls.WebParts { using System; using System.Collections; using System.Collections.Generic; using System.Web.Util; [Serializable] public sealed class PersonalizationStateInfoCollection : ICollection { private Dictionary<Key, int> _indices; private bool _readOnly; // Tried to use the generic type List<T> instead, but it's readonly // implementation returns a different type that is not assignable to List<T>. // That would require to maintain two different fields, one for the readonly // collection when set and one for the modifiable collection version. // // So, the cleaner solution is to use ArrayList, though it might have a // slightly slower perf because of explicit casting. private ArrayList _values; public PersonalizationStateInfoCollection() { _indices = new Dictionary<Key, int>(KeyComparer.Default); _values = new ArrayList(); } public int Count { get { return _values.Count; } } public PersonalizationStateInfo this[string path, string username] { get { if (path == null) { throw new ArgumentNullException("path"); } Key key = new Key(path, username); int index; if (!_indices.TryGetValue(key, out index)) { return null; } return (PersonalizationStateInfo) _values[index]; } } public PersonalizationStateInfo this[int index] { get { return (PersonalizationStateInfo) _values[index]; } } public void Add(PersonalizationStateInfo data) { if (data == null) { throw new ArgumentNullException("data"); } Key key; UserPersonalizationStateInfo userData = data as UserPersonalizationStateInfo; if (userData != null) { key = new Key(userData.Path, userData.Username); } else { key = new Key(data.Path, null); } // VSWhidbey 376063: avoid key duplicate, we check here first before we add. if (_indices.ContainsKey(key)) { if (userData != null) { throw new ArgumentException(SR.GetString(SR.PersonalizationStateInfoCollection_CouldNotAddUserStateInfo, key.Path, key.Username)); } else { throw new ArgumentException(SR.GetString(SR.PersonalizationStateInfoCollection_CouldNotAddSharedStateInfo, key.Path)); } } int pos = _values.Add(data); try { _indices.Add(key, pos); } catch { // Roll back the first addition to make the whole addition atomic _values.RemoveAt(pos); throw; } } public void Clear() { _values.Clear(); _indices.Clear(); } public void CopyTo(PersonalizationStateInfo[] array, int index) { _values.CopyTo(array, index); } public IEnumerator GetEnumerator() { return _values.GetEnumerator(); } public bool IsSynchronized { get { return false; } } public void Remove(string path, string username) { if (path == null) { throw new ArgumentNullException("path"); } Key key = new Key(path, username); int ipos; if (!_indices.TryGetValue(key, out ipos)) { return; } Debug.Assert(ipos >= 0 && ipos < _values.Count); _indices.Remove(key); try { _values.RemoveAt(ipos); } catch { // Roll back the first addition to make the whole addition atomic _indices.Add(key, ipos); throw; } // Readjust the values' indices by -1 where the indices are greater than the removed index ArrayList al = new ArrayList(); foreach(KeyValuePair<Key,int> de in _indices) { if (de.Value > ipos) { al.Add(de.Key); } } foreach (Key k in al) { _indices[k] = ((int) _indices[k]) - 1; } } public void SetReadOnly() { if (_readOnly) { return; } _readOnly = true; _values = ArrayList.ReadOnly(_values); } public object SyncRoot { get { return this; } } void ICollection.CopyTo(Array array, int index) { _values.CopyTo(array, index); } [Serializable] private sealed class Key { public string Path; public string Username; internal Key(string path, string username) { Debug.Assert(path != null); Path = path; Username = username; } } [Serializable] private sealed class KeyComparer : IEqualityComparer<Key> { internal static readonly IEqualityComparer<Key> Default = new KeyComparer(); bool IEqualityComparer<Key>.Equals(Key x, Key y) { return (Compare(x, y) == 0); } int IEqualityComparer<Key>.GetHashCode(Key key) { if (key == null) { return 0; } Debug.Assert(key.Path != null); int pathHashCode = key.Path.ToLowerInvariant().GetHashCode(); int usernameHashCode = 0; if (key.Username != null) { usernameHashCode = key.Username.ToLowerInvariant().GetHashCode(); } return HashCodeCombiner.CombineHashCodes(pathHashCode, usernameHashCode); } private int Compare(Key x, Key y) { if (x == null && y == null) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } int pathDiff = String.Compare(x.Path, y.Path, StringComparison.OrdinalIgnoreCase); if (pathDiff != 0) { return pathDiff; } else { return String.Compare(x.Username, y.Username, StringComparison.OrdinalIgnoreCase); } } } } }
//------------------------------------------------------------------------------ // <copyright file="PointAnimationUsingPath.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using MS.Internal; using System; using System.IO; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Media; using System.Windows.Markup; using System.Windows.Media.Animation; using System.Windows.Media.Composition; namespace System.Windows.Media.Animation { /// <summary> /// This animation can be used inside of a MatrixAnimationCollection to move /// a visual object along a path. /// </summary> public class PointAnimationUsingPath : PointAnimationBase { #region Data private bool _isValid; /// <summary> /// If IsCumulative is set to true, this value represents the value that /// is accumulated with each repeat. It is the end value of the path /// output value for the path. /// </summary> private Vector _accumulatingVector = new Vector(); #endregion #region Constructors /// <summary> /// Creates a new PathPointAnimation class. /// </summary> /// <remarks> /// There is no default PathGeometry so the user must specify one. /// </remarks> public PointAnimationUsingPath() : base() { } #endregion #region Public /// <summary> /// PathGeometry Property /// </summary> public static readonly DependencyProperty PathGeometryProperty = DependencyProperty.Register( "PathGeometry", typeof(PathGeometry), typeof(PointAnimationUsingPath), new PropertyMetadata( (PathGeometry)null)); /// <summary> /// This geometry specifies the path. /// </summary> public PathGeometry PathGeometry { get { return (PathGeometry)GetValue(PathGeometryProperty); } set { SetValue(PathGeometryProperty, value); } } #endregion #region Freezable /// <summary> /// Creates a copy of this PointAnimationUsingPath. /// </summary> /// <returns>The copy.</returns> public new PointAnimationUsingPath Clone() { return (PointAnimationUsingPath)base.Clone(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new PointAnimationUsingPath(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>. /// </summary> protected override void OnChanged() { _isValid = false; base.OnChanged(); } #endregion #region PointAnimationBase /// <summary> /// Calculates the value this animation believes should be the current value for the property. /// </summary> /// <param name="defaultOriginValue"> /// This value is the suggested origin value provided to the animation /// to be used if the animation does not have its own concept of a /// start value. If this animation is the first in a composition chain /// this value will be the snapshot value if one is available or the /// base property value if it is not; otherise this value will be the /// value returned by the previous animation in the chain with an /// animationClock that is not Stopped. /// </param> /// <param name="defaultDestinationValue"> /// This value is the suggested destination value provided to the animation /// to be used if the animation does not have its own concept of an /// end value. This value will be the base value if the animation is /// in the first composition layer of animations on a property; /// otherwise this value will be the output value from the previous /// composition layer of animations for the property. /// </param> /// <param name="animationClock"> /// This is the animationClock which can generate the CurrentTime or /// CurrentProgress value to be used by the animation to generate its /// output value. /// </param> /// <returns> /// The value this animation believes should be the current value for the property. /// </returns> protected override Point GetCurrentValueCore(Point defaultOriginValue, Point defaultDestinationValue, AnimationClock animationClock) { Debug.Assert(animationClock.CurrentState != ClockState.Stopped); PathGeometry pathGeometry = PathGeometry; if (pathGeometry == null) { return defaultDestinationValue; } if (!_isValid) { Validate(); } Point pathPoint; Point pathTangent; pathGeometry.GetPointAtFractionLength(animationClock.CurrentProgress.Value, out pathPoint, out pathTangent); double currentRepeat = (double)(animationClock.CurrentIteration - 1); if ( IsCumulative && currentRepeat > 0) { pathPoint = pathPoint + (_accumulatingVector * currentRepeat); } if (IsAdditive) { return defaultOriginValue + (Vector)pathPoint; } else { return pathPoint; } } /// <summary> /// IsAdditive /// </summary> public bool IsAdditive { get { return (bool)GetValue(IsAdditiveProperty); } set { SetValue(IsAdditiveProperty, value); } } /// <summary> /// IsCumulative /// </summary> public bool IsCumulative { get { return (bool)GetValue(IsCumulativeProperty); } set { SetValue(IsCumulativeProperty, value); } } #endregion #region Private Methods private void Validate() { Debug.Assert(!_isValid); if (IsCumulative) { Point startPoint; Point startTangent; Point endPoint; Point endTangent; PathGeometry pathGeometry = PathGeometry; // Get values at the beginning of the path. pathGeometry.GetPointAtFractionLength(0.0, out startPoint, out startTangent); // Get values at the end of the path. pathGeometry.GetPointAtFractionLength(1.0, out endPoint, out endTangent); _accumulatingVector.X = endPoint.X - startPoint.X; _accumulatingVector.Y = endPoint.Y - startPoint.Y; } _isValid = true; } #endregion } }
using AutoBogus.NSubstitute; using Bogus; using FluentAssertions; using System; using System.Linq.Expressions; using Xunit; namespace AutoBogus.Tests { public class AutoConfigBuilderFixture { private Faker _faker; private AutoConfig _config; private AutoConfigBuilder _builder; private interface ITestBuilder { } public AutoConfigBuilderFixture() { _faker = new Faker(); _config = new AutoConfig(); _builder = new AutoConfigBuilder(_config); } public class WithLocale : AutoConfigBuilderFixture { [Fact] public void Should_Set_Config_Locale() { var locale = _faker.Random.String(); _builder.WithLocale<ITestBuilder>(locale, null); _config.Locale.Should().Be(locale); } [Fact] public void Should_Set_Config_Locale_To_Default_If_Null() { _config.Locale = _faker.Random.String(); _builder.WithLocale<ITestBuilder>(null, null); _config.Locale.Should().Be(AutoConfig.DefaultLocale); } } public class WithRepeatCount : AutoConfigBuilderFixture { [Fact] public void Should_Set_Config_RepeatCount() { var count = _faker.Random.Int(); _builder.WithRepeatCount<ITestBuilder>(context => count, null); _config.RepeatCount.Invoke(null).Should().Be(count); } [Fact] public void Should_Set_Config_RepeatCount_To_Default_If_Null() { var count = AutoConfig.DefaultRepeatCount.Invoke(null); _builder.WithRepeatCount<ITestBuilder>(null, null); _config.RepeatCount.Invoke(null).Should().Be(count); } } public class WithRecursiveDepth : AutoConfigBuilderFixture { [Fact] public void Should_Set_Config_RecursiveDepth() { var depth = _faker.Random.Int(); _builder.WithRecursiveDepth<ITestBuilder>(context => depth, null); _config.RecursiveDepth.Invoke(null).Should().Be(depth); } [Fact] public void Should_Set_Config_RecursiveDepth_To_Default_If_Null() { var depth = AutoConfig.DefaultRecursiveDepth.Invoke(null); _builder.WithRecursiveDepth<ITestBuilder>(null, null); _config.RecursiveDepth.Invoke(null).Should().Be(depth); } } public class WithTreeDepth : AutoConfigBuilderFixture { [Fact] public void Should_Set_Config_TreeDepth() { var depth = _faker.Random.Int(); _builder.WithTreeDepth<ITestBuilder>(context => depth, null); _config.TreeDepth.Invoke(null).Should().Be(depth); } [Fact] public void Should_Set_Config_TreeDepth_To_Default_If_Null() { var depth = AutoConfig.DefaultTreeDepth.Invoke(null); _builder.WithTreeDepth<ITestBuilder>(null, null); _config.TreeDepth.Invoke(null).Should().Be(depth); } } public class WithBinder : AutoConfigBuilderFixture { [Fact] public void Should_Set_Config_Binder() { var binder = new NSubstituteBinder(); _builder.WithBinder<ITestBuilder>(binder, null); _config.Binder.Should().Be(binder); } [Fact] public void Should_Set_Config_Binder_To_Default_If_Null() { _config.Binder = new NSubstituteBinder(); _builder.WithBinder<ITestBuilder>(null, null); _config.Binder.Should().BeOfType<AutoBinder>(); } } public class WithFakerHub : AutoConfigBuilderFixture { [Fact] public void Should_Set_Config_FakerHub() { var fakerHub = new Faker(); _builder.WithFakerHub<ITestBuilder>(fakerHub, null); _config.FakerHub.Should().Be(fakerHub); } } public class WithSkip_Type : AutoConfigBuilderFixture { [Fact] public void Should_Not_Add_Type_If_Already_Added() { var type1 = typeof(int); var type2 = typeof(int); _config.SkipTypes.Add(type1); _builder.WithSkip<ITestBuilder>(type2, null); _config.SkipTypes.Should().ContainSingle(); } [Fact] public void Should_Add_Type_To_Skip() { var type1 = typeof(int); var type2 = typeof(string); _config.SkipTypes.Add(type1); _builder.WithSkip<ITestBuilder>(type2, null); _config.SkipTypes.Should().BeEquivalentTo(new[] { type1, type2 }); } } public class WithSkip_TypePath : AutoConfigBuilderFixture { private sealed class TestSkip { public string Value { get; set; } } [Fact] public void Should_Not_Add_Member_If_Already_Added() { var type = typeof(TestSkip); var member = $"{type.FullName}.Value"; _config.SkipPaths.Add(member); _builder.WithSkip<ITestBuilder>(type, "Value", null); _config.SkipPaths.Should().ContainSingle(); } [Fact] public void Should_Add_MemberName_To_Skip() { var type = typeof(TestSkip); var path = _faker.Random.String(); _config.SkipPaths.Add(path); _builder.WithSkip<ITestBuilder>(type, "Value", null); _config.SkipPaths.Should().BeEquivalentTo(new[] { path, $"{type.FullName}.Value" }); } } public class WithSkip_Path : AutoConfigBuilderFixture { private sealed class TestSkip { public string Value { get; set; } } [Fact] public void Should_Not_Add_Member_If_Already_Added() { var type = typeof(TestSkip); var member = $"{type.FullName}.Value"; _config.SkipPaths.Add(member); _builder.WithSkip<ITestBuilder, TestSkip>("Value", null); _config.SkipPaths.Should().ContainSingle(); } [Fact] public void Should_Add_MemberName_To_Skip() { var type = typeof(TestSkip); var path = _faker.Random.String(); _config.SkipPaths.Add(path); _builder.WithSkip<ITestBuilder, TestSkip>("Value", null); _config.SkipPaths.Should().BeEquivalentTo(new[] { path, $"{type.FullName}.Value" }); } } public class WithOverride : AutoConfigBuilderFixture { private class TestGeneratorOverride : AutoGeneratorOverride { public override bool CanOverride(AutoGenerateContext context) { return false; } public override void Generate(AutoGenerateOverrideContext context) { } } [Fact] public void Should_Not_Add_Null_Override() { _builder.WithOverride<ITestBuilder>(null, null); _config.Overrides.Should().BeEmpty(); } [Fact] public void Should_Not_Add_Override_If_Already_Added() { var generatorOverride = new TestGeneratorOverride(); _config.Overrides.Add(generatorOverride); _builder.WithOverride<ITestBuilder>(generatorOverride, null); _config.Overrides.Should().ContainSingle(); } [Fact] public void Should_Add_Override_If_Equivalency_Is_Different() { var generatorOverride1 = new TestGeneratorOverride(); var generatorOverride2 = new TestGeneratorOverride(); _config.Overrides.Add(generatorOverride1); _builder.WithOverride<ITestBuilder>(generatorOverride2, null); _config.Overrides.Should().BeEquivalentTo(new[] { generatorOverride1, generatorOverride2 }); } } public class WithArgs : AutoConfigBuilderFixture { [Fact] public void Should_Set_Args() { var args = new object[] { _faker.Random.Int(), _faker.Random.String() }; _builder.WithArgs<ITestBuilder>(args, null); _builder.Args.Should().BeSameAs(args); } } } }
// // assembly: System // namespace: System.Text.RegularExpressions // file: syntax.cs // // author: Dan Lewis (dlewis@gmx.co.uk) // (c) 2002 // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; namespace System.Text.RegularExpressions.Syntax { // collection classes class ExpressionCollection : CollectionBase { public void Add (Expression e) { List.Add (e); } public Expression this[int i] { get { return (Expression)List[i]; } set { List[i] = value; } } protected override void OnValidate (object o) { // allow null elements } } // abstract classes abstract class Expression { public abstract void Compile (ICompiler cmp, bool reverse); public abstract void GetWidth (out int min, out int max); public int GetFixedWidth () { int min, max; GetWidth (out min, out max); if (min == max) return min; return -1; } public virtual AnchorInfo GetAnchorInfo (bool reverse) { return new AnchorInfo (this, GetFixedWidth ()); } public virtual bool IsComplex () { return true; } } // composite expressions abstract class CompositeExpression : Expression { public CompositeExpression () { expressions = new ExpressionCollection (); } protected ExpressionCollection Expressions { get { return expressions; } } protected void GetWidth (out int min, out int max, int count) { min = Int32.MaxValue; max = 0; bool empty = true; for (int i = 0; i < count; ++ i) { Expression e = Expressions[i]; if (e == null) continue; empty = false; int a, b; e.GetWidth (out a, out b); if (a < min) min = a; if (b > max) max = b; } if (empty) min = max = 0; } private ExpressionCollection expressions; } // groups class Group : CompositeExpression { public Group () { } public Expression Expression { get { return Expressions[0]; } set { Expressions[0] = value; } } public void AppendExpression (Expression e) { Expressions.Add (e); } public override void Compile (ICompiler cmp, bool reverse) { int count = Expressions.Count; for (int i = 0; i < count; ++ i) { Expression e; if (reverse) e = Expressions[count - i - 1]; else e = Expressions[i]; e.Compile (cmp, reverse); } } public override void GetWidth (out int min, out int max) { min = 0; max = 0; foreach (Expression e in Expressions) { int a, b; e.GetWidth (out a, out b); min += a; if (max == Int32.MaxValue || b == Int32.MaxValue) max = Int32.MaxValue; else max += b; } } public override AnchorInfo GetAnchorInfo (bool reverse) { int ptr; int width = GetFixedWidth (); ArrayList infos = new ArrayList (); IntervalCollection segments = new IntervalCollection (); // accumulate segments ptr = 0; //foreach (Expression e in Expressions) { int count = Expressions.Count; for (int i = 0; i < count; ++ i) { Expression e; if (reverse) e = Expressions [count - i - 1]; else e = Expressions [i]; AnchorInfo info = e.GetAnchorInfo (reverse); infos.Add (info); if (info.IsPosition) return new AnchorInfo (this, ptr + info.Offset, width, info.Position); if (info.IsSubstring) segments.Add (info.GetInterval (ptr)); if (info.IsUnknownWidth) break; ptr += info.Width; } // normalize and find the longest segment segments.Normalize (); Interval longest = Interval.Empty; foreach (Interval segment in segments) { if (segment.Size > longest.Size) longest = segment; } // now chain the substrings that made this segment together if (!longest.IsEmpty) { string str = ""; ArrayList strs = new ArrayList(); bool ignore = false; ptr = 0; //foreach (AnchorInfo info in infos) { for (int i = 0; i < infos.Count; ++ i) { AnchorInfo info; info = (AnchorInfo)infos[i]; if (info.IsSubstring && longest.Contains (info.GetInterval (ptr))) { //str += info.Substring; // TODO mark subexpressions strs.Add(info.Substring); ignore |= info.IgnoreCase; } if (info.IsUnknownWidth) break; ptr += info.Width; } for (int i = 0; i< strs.Count; ++i) { if (reverse) str += strs [strs.Count - i - 1]; else str += strs [i]; } return new AnchorInfo (this, longest.low, width, str, ignore); } return new AnchorInfo (this, width); } public override bool IsComplex () { bool comp = false; foreach (Expression e in Expressions) { comp |= e.IsComplex (); } return comp | GetFixedWidth () <= 0; } } class RegularExpression : Group { public RegularExpression () { group_count = 0; } public int GroupCount { get { return group_count; } set { group_count = value; } } public override void Compile (ICompiler cmp, bool reverse) { // info block int min, max; GetWidth (out min, out max); cmp.EmitInfo (group_count, min, max); // anchoring expression AnchorInfo info = GetAnchorInfo (reverse); //if (reverse) // info = new AnchorInfo (this, GetFixedWidth ()); // FIXME LinkRef pattern = cmp.NewLink (); cmp.EmitAnchor (reverse, info.Offset, pattern); if (info.IsPosition) cmp.EmitPosition (info.Position); else if (info.IsSubstring) cmp.EmitString (info.Substring, info.IgnoreCase, reverse); cmp.EmitTrue (); // pattern cmp.ResolveLink (pattern); base.Compile (cmp, reverse); cmp.EmitTrue (); } private int group_count; } class CapturingGroup : Group { public CapturingGroup () { this.gid = 0; this.name = null; } public int Number { get { return gid; } set { gid = value; } } public string Name { get { return name; } set { name = value; } } public bool IsNamed { get { return name != null; } } public override void Compile (ICompiler cmp, bool reverse) { cmp.EmitOpen (gid); base.Compile (cmp, reverse); cmp.EmitClose (gid); } public override bool IsComplex () { return true; } private int gid; private string name; } class BalancingGroup : CapturingGroup { public BalancingGroup () { this.balance = null; } public CapturingGroup Balance { get { return balance; } set { balance = value; } } public override void Compile (ICompiler cmp, bool reverse) { // can't invoke Group.Compile from here :( // so I'll just repeat the code LinkRef tail = cmp.NewLink (); cmp.EmitBalanceStart (this.Number, balance.Number, this.IsNamed, tail); int count = Expressions.Count; for (int i = 0; i < count; ++ i) { Expression e; if (reverse) e = Expressions[count - i - 1]; else e = Expressions[i]; e.Compile (cmp, reverse); } cmp.EmitBalance (); cmp.ResolveLink(tail); } private CapturingGroup balance; } class NonBacktrackingGroup : Group { public NonBacktrackingGroup () { } public override void Compile (ICompiler cmp, bool reverse) { LinkRef tail = cmp.NewLink (); cmp.EmitSub (tail); base.Compile (cmp, reverse); cmp.EmitTrue (); cmp.ResolveLink (tail); } public override bool IsComplex () { return true; } } // repetition class Repetition : CompositeExpression { public Repetition (int min, int max, bool lazy) { Expressions.Add (null); this.min = min; this.max = max; this.lazy = lazy; } public Expression Expression { get { return Expressions[0]; } set { Expressions[0] = value; } } public int Minimum { get { return min; } set { min = value; } } public int Maximum { get { return max; } set { max = value; } } public bool Lazy { get { return lazy; } set { lazy = value; } } public override void Compile (ICompiler cmp, bool reverse) { if (Expression.IsComplex ()) { LinkRef until = cmp.NewLink (); cmp.EmitRepeat (min, max, lazy, until); Expression.Compile (cmp, reverse); cmp.EmitUntil (until); } else { LinkRef tail = cmp.NewLink (); cmp.EmitFastRepeat (min, max, lazy, tail); Expression.Compile (cmp, reverse); cmp.EmitTrue (); cmp.ResolveLink (tail); } } public override void GetWidth (out int min, out int max) { Expression.GetWidth (out min, out max); min = min * this.min; if (max == Int32.MaxValue || this.max == 0xffff) max = Int32.MaxValue; else max = max * this.max; } public override AnchorInfo GetAnchorInfo (bool reverse) { int width = GetFixedWidth (); if (Minimum == 0) return new AnchorInfo (this, width); AnchorInfo info = Expression.GetAnchorInfo (reverse); if (info.IsPosition) return new AnchorInfo (this, info.Offset, width, info.Position); if (info.IsSubstring) { if (info.IsComplete) { string str = ""; for (int i = 0; i < Minimum; ++ i) str += info.Substring; return new AnchorInfo (this, 0, width, str, info.IgnoreCase); } return new AnchorInfo (this, info.Offset, width, info.Substring, info.IgnoreCase); } return new AnchorInfo (this, width); } private int min, max; private bool lazy; } // assertions abstract class Assertion : CompositeExpression { public Assertion () { Expressions.Add (null); // true expression Expressions.Add (null); // false expression } public Expression TrueExpression { get { return Expressions[0]; } set { Expressions[0] = value; } } public Expression FalseExpression { get { return Expressions[1]; } set { Expressions[1] = value; } } public override void GetWidth (out int min, out int max) { GetWidth (out min, out max, 2); if (TrueExpression == null || FalseExpression == null) min = 0; } } class CaptureAssertion : Assertion { public CaptureAssertion () { } public CapturingGroup CapturingGroup { get { return group; } set { group = value; } } public override void Compile (ICompiler cmp, bool reverse) { int gid = group.Number; LinkRef tail = cmp.NewLink (); if (FalseExpression == null) { // IfDefined :1 // <yes_exp> // 1: <tail> cmp.EmitIfDefined (gid, tail); TrueExpression.Compile (cmp, reverse); } else { // IfDefined :1 // <yes_expr> // Jump :2 // 1: <no_expr> // 2: <tail> LinkRef false_expr = cmp.NewLink (); cmp.EmitIfDefined (gid, false_expr); TrueExpression.Compile (cmp, reverse); cmp.EmitJump (tail); cmp.ResolveLink (false_expr); FalseExpression.Compile (cmp, reverse); } cmp.ResolveLink (tail); } public override bool IsComplex () { bool comp = false; if (TrueExpression != null) comp |= TrueExpression.IsComplex (); if (FalseExpression != null) comp |= FalseExpression.IsComplex (); return comp | GetFixedWidth () <= 0; } private CapturingGroup group; } class ExpressionAssertion : Assertion { public ExpressionAssertion () { Expressions.Add (null); // test expression } public bool Reverse { get { return reverse; } set { reverse = value; } } public bool Negate { get { return negate; } set { negate = value; } } public Expression TestExpression { get { return Expressions[2]; } set { Expressions[2] = value; } } public override void Compile (ICompiler cmp, bool reverse) { LinkRef true_expr = cmp.NewLink (); LinkRef false_expr = cmp.NewLink (); // test op: positive / negative if (!negate) cmp.EmitTest (true_expr, false_expr); else cmp.EmitTest (false_expr, true_expr); // test expression: lookahead / lookbehind TestExpression.Compile (cmp, this.reverse); cmp.EmitTrue (); // target expressions if (TrueExpression == null) { // (?= ...) // Test :1, :2 // <test_expr> // :2 False // :1 <tail> cmp.ResolveLink (false_expr); cmp.EmitFalse (); cmp.ResolveLink (true_expr); } else { cmp.ResolveLink (true_expr); TrueExpression.Compile (cmp, reverse); if (FalseExpression == null) { // (?(...) ...) // Test :1, :2 // <test_expr> // :1 <yes_expr> // :2 <tail> cmp.ResolveLink (false_expr); } else { // (?(...) ... | ...) // Test :1, :2 // <test_expr> // :1 <yes_expr> // Jump :3 // :2 <no_expr> // :3 <tail> LinkRef tail = cmp.NewLink (); cmp.EmitJump (tail); cmp.ResolveLink (false_expr); FalseExpression.Compile (cmp, reverse); cmp.ResolveLink (tail); } } } private bool reverse, negate; } // alternation class Alternation : CompositeExpression { public Alternation () { } public ExpressionCollection Alternatives { get { return Expressions; } } public void AddAlternative (Expression e) { Alternatives.Add (e); } public override void Compile (ICompiler cmp, bool reverse) { // LinkRef next = cmp.NewLink (); LinkRef tail = cmp.NewLink (); foreach (Expression e in Alternatives) { LinkRef next = cmp.NewLink (); cmp.EmitBranch (next); e.Compile (cmp, reverse); cmp.EmitJump (tail); cmp.ResolveLink (next); cmp.EmitBranchEnd(); } cmp.EmitFalse (); cmp.ResolveLink (tail); cmp.EmitAlternationEnd(); } public override void GetWidth (out int min, out int max) { GetWidth (out min, out max, Alternatives.Count); } public override bool IsComplex () { bool comp = false; foreach (Expression e in Alternatives) { comp |= e.IsComplex (); } return comp | GetFixedWidth () <= 0; } } // terminal expressions class Literal : Expression { public Literal (string str, bool ignore) { this.str = str; this.ignore = ignore; } public string String { get { return str; } set { str = value; } } public bool IgnoreCase { get { return ignore; } set { ignore = value; } } public override void Compile (ICompiler cmp, bool reverse) { if (str.Length == 0) return; if (str.Length == 1) cmp.EmitCharacter (str[0], false, ignore, reverse); else cmp.EmitString (str, ignore, reverse); } public override void GetWidth (out int min, out int max) { min = max = str.Length; } public override AnchorInfo GetAnchorInfo (bool reverse) { return new AnchorInfo (this, 0, str.Length, str, ignore); } public override bool IsComplex () { return false; } private string str; private bool ignore; } class PositionAssertion : Expression { public PositionAssertion (Position pos) { this.pos = pos; } public Position Position { get { return pos; } set { pos = value; } } public override void Compile (ICompiler cmp, bool reverse) { cmp.EmitPosition (pos); } public override void GetWidth (out int min, out int max) { min = max = 0; } public override bool IsComplex () { return false; } public override AnchorInfo GetAnchorInfo (bool revers) { switch (pos) { case Position.StartOfString: case Position.StartOfLine: case Position.StartOfScan: return new AnchorInfo (this, 0, 0, pos); default: return new AnchorInfo (this, 0); } } private Position pos; } class Reference : Expression { public Reference (bool ignore) { this.ignore = ignore; } public CapturingGroup CapturingGroup { get { return group; } set { group = value; } } public bool IgnoreCase { get { return ignore; } set { ignore = value; } } public override void Compile (ICompiler cmp, bool reverse) { cmp.EmitReference (group.Number, ignore, reverse); } public override void GetWidth (out int min, out int max) { //group.GetWidth (out min, out max); // TODO set width to referenced group for non-cyclical references min = 0; max = Int32.MaxValue; } public override bool IsComplex () { return true; // FIXME incorporate cyclic check } private CapturingGroup group; private bool ignore; } class CharacterClass : Expression { public CharacterClass (bool negate, bool ignore) { this.negate = negate; this.ignore = ignore; intervals = new IntervalCollection (); // initialize pos/neg category arrays int cat_size = (int) Category.LastValue; pos_cats = new BitArray (cat_size); neg_cats = new BitArray (cat_size); } public CharacterClass (Category cat, bool negate) : this (false, false) { this.AddCategory (cat, negate); } public bool Negate { get { return negate; } set { negate = value; } } public bool IgnoreCase { get { return ignore; } set { ignore = value; } } public void AddCategory (Category cat, bool negate) { int n = (int)cat; if (negate) { // use BitArray.Set for speedups // neg_cats[n] = true; neg_cats.Set( n, true ); } else { // use BitArray.Set for speedups //pos_cats[n] = true; pos_cats.Set( n, true ); } } public void AddCharacter (char c) { // TODO: this is certainly not the most efficient way of doing things // TODO: but at least it produces correct results. AddRange (c, c); } public void AddRange (char lo, char hi) { Interval new_interval = new Interval (lo, hi); // ignore case is on. we must make sure our interval does not // use upper case. if it does, we must normalize the upper case // characters into lower case. if (ignore) { if (upper_case_characters.Intersects (new_interval)) { Interval partial_new_interval; if (new_interval.low < upper_case_characters.low) { partial_new_interval = new Interval (upper_case_characters.low + distance_between_upper_and_lower_case, new_interval.high + distance_between_upper_and_lower_case); new_interval.high = upper_case_characters.low - 1; } else { partial_new_interval = new Interval (new_interval.low + distance_between_upper_and_lower_case, upper_case_characters.high + distance_between_upper_and_lower_case); new_interval.low = upper_case_characters.high + 1; } intervals.Add (partial_new_interval); } else if (upper_case_characters.Contains (new_interval)) { new_interval.high += distance_between_upper_and_lower_case; new_interval.low += distance_between_upper_and_lower_case; } } intervals.Add (new_interval); } public override void Compile (ICompiler cmp, bool reverse) { // create the meta-collection IntervalCollection meta = intervals.GetMetaCollection (new IntervalCollection.CostDelegate (GetIntervalCost)); // count ops int count = meta.Count; for (int i = 0; i < pos_cats.Length; ++ i) { // use BitArray.Get instead of indexer for speedups //if (pos_cats[i]) ++ count; //if (neg_cats[i]) ++ count; if (pos_cats.Get(i)) ++ count; if (neg_cats.Get(i)) ++ count; } if (count == 0) return; // emit in op for |meta| > 1 LinkRef tail = cmp.NewLink (); if (count > 1) cmp.EmitIn (tail); // emit categories for (int i = 0; i < pos_cats.Length; ++ i) { // use BitArray.Get instead of indexer for speedups //if (pos_cats[i]) { if (pos_cats.Get(i)) { //if (neg_cats [i]) if (neg_cats.Get(i)) cmp.EmitCategory (Category.AnySingleline, negate, reverse); else cmp.EmitCategory ((Category)i, negate, reverse); // } else if (neg_cats[i]) { } else if (neg_cats.Get(i)) { cmp.EmitCategory ((Category)i, !negate, reverse); } } // emit character/range/sets from meta-collection foreach (Interval a in meta) { if (a.IsDiscontiguous) { // Set BitArray bits = new BitArray (a.Size); foreach (Interval b in intervals) { if (a.Contains (b)) { for (int i = b.low; i <= b.high; ++ i) // use BitArray.Get instead of indexer for speedups : bits[i - a.low] = true; bits.Set( i - a.low, true ); } } cmp.EmitSet ((char)a.low, bits, negate, ignore, reverse); } else if (a.IsSingleton) // Character cmp.EmitCharacter ((char)a.low, negate, ignore, reverse); else // Range cmp.EmitRange ((char)a.low, (char)a.high, negate, ignore, reverse); } // finish up if (count > 1) { if (negate) cmp.EmitTrue (); else cmp.EmitFalse (); cmp.ResolveLink (tail); } } public override void GetWidth (out int min, out int max) { min = max = 1; } public override bool IsComplex () { return false; } // private private static double GetIntervalCost (Interval i) { // use op length as cost metric (=> optimize for space) if (i.IsDiscontiguous) return 3 + ((i.Size + 0xf) >> 4); // Set else if (i.IsSingleton) return 2; // Character else return 3; // Range } private static Interval upper_case_characters = new Interval ((char)65, (char)90); private const int distance_between_upper_and_lower_case = 32; private bool negate, ignore; private BitArray pos_cats, neg_cats; private IntervalCollection intervals; } class AnchorInfo { private Expression expr; private Position pos; private int offset; private string str; private int width; private bool ignore; public AnchorInfo (Expression expr, int width) { this.expr = expr; this.offset = 0; this.width = width; this.str = null; this.ignore = false; this.pos = Position.Any; } public AnchorInfo (Expression expr, int offset, int width, string str, bool ignore) { this.expr = expr; this.offset = offset; this.width = width; this.str = ignore ? str.ToLower () : str; this.ignore = ignore; this.pos = Position.Any; } public AnchorInfo (Expression expr, int offset, int width, Position pos) { this.expr = expr; this.offset = offset; this.width = width; this.pos = pos; this.str = null; this.ignore = false; } public Expression Expression { get { return expr; } } public int Offset { get { return offset; } } public int Width { get { return width; } } public int Length { get { return (str != null) ? str.Length : 0; } } public bool IsUnknownWidth { get { return width < 0; } } public bool IsComplete { get { return Length == Width; } } public string Substring { get { return str; } } public bool IgnoreCase { get { return ignore; } } public Position Position { get { return pos; } } public bool IsSubstring { get { return str != null; } } public bool IsPosition { get { return pos != Position.Any; } } public Interval GetInterval () { return GetInterval (0); } public Interval GetInterval (int start) { if (!IsSubstring) return Interval.Empty; return new Interval (start + Offset, start + Offset + Length - 1); } } }
using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text; namespace Fluid.Drawing.GdiPlus { [StructLayout(LayoutKind.Sequential)] public struct GpGraphics { public static implicit operator IntPtr(GpGraphics obj) { return obj.ptr; } internal IntPtr ptr; public IntPtr Handle { get { return ptr; } } } [StructLayout(LayoutKind.Sequential)] public struct GpMatrix { IntPtr ptr; } [StructLayout(LayoutKind.Sequential)] public struct GpPath { IntPtr ptr; public static implicit operator IntPtr(GpPath obj) { return obj.ptr; } public static implicit operator GpPath(string n) { if (n == null) return new GpPath(); else throw new ArgumentException(); } public IntPtr Handle { get { return ptr; } } } [StructLayout(LayoutKind.Sequential)] public struct GpFont { IntPtr ptr; public static implicit operator IntPtr(GpFont obj) { return obj.ptr; } } [StructLayout(LayoutKind.Sequential)] public struct GpPen { IntPtr ptr; public static implicit operator IntPtr(GpPen obj) { return obj.ptr; } public static implicit operator GpPen(string n) { if (n == null) return new GpPen(); else throw new ArgumentException(); } } [StructLayout(LayoutKind.Sequential)] public struct GpBrush { internal IntPtr ptr; public static implicit operator IntPtr(GpBrush obj) { return obj.ptr; } } [StructLayout(LayoutKind.Sequential)] public struct GpHatch { IntPtr ptr; public static implicit operator GpBrush(GpHatch me) { GpBrush br = new GpBrush(); br.ptr = me.ptr; return br; } public static explicit operator GpHatch(GpBrush br) { GpHatch n = new GpHatch(); n.ptr = br.ptr; return n; } } [StructLayout(LayoutKind.Sequential)] public struct GpTexture { IntPtr ptr; public static implicit operator GpBrush(GpTexture me) { GpBrush br = new GpBrush(); br.ptr = me.ptr; return br; } public static explicit operator GpTexture(GpBrush br) { GpTexture n = new GpTexture(); n.ptr = br.ptr; return n; } } [StructLayout(LayoutKind.Sequential)] public struct GpSolidFill { IntPtr ptr; public static implicit operator GpBrush(GpSolidFill me) { GpBrush br = new GpBrush(); br.ptr = me.ptr; return br; } public static explicit operator GpSolidFill(GpBrush br) { GpSolidFill n = new GpSolidFill(); n.ptr = br.ptr; return n; } } [StructLayout(LayoutKind.Sequential)] public struct GpPathGradient { IntPtr ptr; public static implicit operator GpBrush(GpPathGradient me) { GpBrush br = new GpBrush(); br.ptr = me.ptr; return br; } public static explicit operator GpPathGradient(GpBrush br) { GpPathGradient n = new GpPathGradient(); n.ptr = br.ptr; return n; } } [StructLayout(LayoutKind.Sequential)] public struct GpLineGradient { IntPtr ptr; public static implicit operator GpBrush(GpLineGradient me) { GpBrush br = new GpBrush(); br.ptr = me.ptr; return br; } public static explicit operator GpLineGradient(GpBrush br) { GpLineGradient n = new GpLineGradient(); n.ptr = br.ptr; return n; } } [StructLayout(LayoutKind.Sequential)] public struct GpRegion { public IntPtr ptr; } [StructLayout(LayoutKind.Sequential)] public struct GpImage { IntPtr ptr; public static implicit operator GpImage(string n) { if (n == null) return new GpImage(); else throw new ArgumentException(); } public static implicit operator GpImage(IntPtr p) { GpImage img = new GpImage(); img.ptr = p; return img; } public static implicit operator IntPtr(GpImage obj) { return obj.ptr; } } [StructLayout(LayoutKind.Sequential)] public struct GpBitmap { internal IntPtr ptr; public static explicit operator IntPtr(GpBitmap bm) { return bm.ptr; } public static explicit operator GpImage(GpBitmap bm) { GpImage img = (GpImage)(IntPtr)bm; return img; } public static implicit operator GpBitmap(IntPtr p) { GpBitmap bm = new GpBitmap(); bm.ptr = p; return bm; } } [StructLayout(LayoutKind.Sequential)] public struct GpPathData { public int Count; public PointF[] Points; public byte[] Types; } [StructLayout(LayoutKind.Sequential)] public struct GpCachedBitmap { IntPtr ptr; } [StructLayout(LayoutKind.Sequential)] public struct GpLineCap { IntPtr ptr; public static implicit operator IntPtr(GpLineCap obj) { return obj.ptr; } } [StructLayout(LayoutKind.Sequential)] public struct GpCustomLineCap { IntPtr ptr; public static implicit operator IntPtr(GpCustomLineCap obj) { return obj.ptr; } } [StructLayout(LayoutKind.Sequential)] public struct GpImageAttributes { IntPtr ptr; } [StructLayout(LayoutKind.Sequential)] public struct GpFontFamily { IntPtr ptr; } [StructLayout(LayoutKind.Sequential)] public struct GpStringFormat { IntPtr ptr; } public enum GpStatus { Ok = 0, GenericError = 1, InvalidParameter = 2, OutOfMemory = 3, ObjectBusy = 4, InsufficientBuffer = 5, NotImplemented = 6, Win32Error = 7, WrongState = 8, Aborted = 9, FileNotFound = 10, ValueOverflow = 11, AccessDenied = 12, UnknownImageFormat = 13, FontFamilyNotFound = 14, FontStyleNotFound = 15, NotTrueTypeFont = 16, UnsupportedGdiplusVersion = 17, GdiplusNotInitialized = 18, PropertyNotFound = 19, PropertyNotSupported = 20, } [StructLayout(LayoutKind.Sequential)] public struct HDC { private HDC(IntPtr v) { val = v; } public IntPtr val; public static implicit operator IntPtr(HDC hdc) { return hdc.val; } public static implicit operator HDC(IntPtr hdc) { return new HDC(hdc); } } [StructLayout(LayoutKind.Sequential)] public struct HANDLE { private HANDLE(IntPtr v) { val = v; } public IntPtr val; public static implicit operator IntPtr(HANDLE hdc) { return hdc.val; } public static implicit operator HANDLE(IntPtr hdc) { return new HANDLE(hdc); } } [StructLayout(LayoutKind.Sequential)] public struct HWND { private HWND(IntPtr v) { val = v; } public IntPtr val; public static implicit operator IntPtr(HWND hdc) { return hdc.val; } public static implicit operator HWND(IntPtr hdc) { return new HWND(hdc); } } [StructLayout(LayoutKind.Sequential)] public struct HRGN { private HRGN(IntPtr v) { val = v; } public IntPtr val; public static implicit operator IntPtr(HRGN hdc) { return hdc.val; } public static implicit operator HRGN(IntPtr hdc) { return new HRGN(hdc); } } [StructLayout(LayoutKind.Sequential)] public struct HFONT { private HFONT(IntPtr v) { val = v; } public IntPtr val; public static implicit operator IntPtr(HFONT hdc) { return hdc.val; } public static implicit operator HFONT(IntPtr hdc) { return new HFONT(hdc); } } [StructLayout(LayoutKind.Sequential)] public struct HBITMAP { private HBITMAP(IntPtr v) { val = v; } public IntPtr val; public static implicit operator IntPtr(HBITMAP v) { return v.val; } public static implicit operator HBITMAP(IntPtr v) { return new HBITMAP(v); } } public enum PROPID : ushort { } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.IO; using System.Net; using System.Collections.Generic; using System.Text; using System.Web; using WebsitePanel.Server.Utils; using WebsitePanel.Providers.Utils; using Microsoft.Win32; namespace WebsitePanel.Providers.DNS { public class SimpleDNS : HostingServiceProviderBase, IDnsServer { #region Properties protected int ExpireLimit { get { return ProviderSettings.GetInt("ExpireLimit"); } } protected int MinimumTTL { get { return ProviderSettings.GetInt("MinimumTTL"); } } protected int RefreshInterval { get { return ProviderSettings.GetInt("RefreshInterval"); } } protected int RetryDelay { get { return ProviderSettings.GetInt("RetryDelay"); } } protected string SimpleDnsUrl { get { return ProviderSettings["SimpleDnsUrl"]; } } protected string AdminLogin { get { return ProviderSettings["AdminLogin"]; } } protected string SimpleDnsPassword { get { return ProviderSettings["Password"]; } } #endregion #region Zones public virtual bool ZoneExists(string zoneName) { try { string response = ExecuteDnsQuery("getzone", "zone=" + zoneName); return true; } catch (WebException ex) { Log.WriteWarning(ex.ToString()); return false; } } public virtual string[] GetZones() { string response = ExecuteDnsQuery("zonelist", null); string[] lines = response.Split('\r', '\n'); List<string> zones = new List<string>(); foreach (string line in lines) { // prepare line if (line.Trim() != "") zones.Add(RemoveTrailingDot(line)); } return zones.ToArray(); } public virtual void AddPrimaryZone(string zoneName, string[] secondaryServers) { // CREATE PRIMARY DNS ZONE List<DnsRecord> records = new List<DnsRecord>(); // add "Zone transfers" record if (secondaryServers != null && secondaryServers.Length != 0) { DnsRecord zt = new DnsRecord(); zt.RecordType = DnsRecordType.Other; zt.RecordName = ""; if (secondaryServers.Length == 1 && secondaryServers[0] == "*") zt.RecordText = ";$AllowZT *"; else zt.RecordText = ";$AllowZT " + String.Join(" ", secondaryServers); records.Add(zt); } // add SOA record DnsSOARecord soa = new DnsSOARecord(); soa.RecordType = DnsRecordType.SOA; soa.RecordName = ""; soa.PrimaryNsServer = System.Net.Dns.GetHostEntry("LocalHost").HostName; soa.PrimaryPerson = "hostmaster";//"hostmaster." + zoneName; records.Add(soa); // add DNS zone UpdateZone(zoneName, records); } public virtual void AddSecondaryZone(string zoneName, string[] masterServers) { //;$PrimaryIP 127.0.0.1 //;$MinimumTTL 0 // CREATE SECONDARY DNS ZONE List<DnsRecord> records = new List<DnsRecord>(); // add DNS zone UpdateZone(zoneName, records, masterServers); } public virtual DnsRecord[] GetZoneRecords(string zoneName) { List<DnsRecord> records = GetZoneRecordsArrayList(zoneName); List<DnsRecord> filteredRecords = new List<DnsRecord>(); foreach (DnsRecord record in records) { if (record.RecordType != DnsRecordType.SOA && record.RecordType != DnsRecordType.Other) filteredRecords.Add(record); } return filteredRecords.ToArray(); } private List<DnsRecord> GetZoneRecordsArrayList(string zoneName) { string response = ExecuteDnsQuery("getzone", "zone=" + zoneName); if (response.IndexOf("(404) Not Found") != -1) return new List<DnsRecord>(); // parse zone file return ParseZoneFileToArrayList(zoneName, response); } public virtual void DeleteZone(string zoneName) { ExecuteDnsQuery("removezone", "zone=" + zoneName); } #endregion #region Resource records public virtual void AddZoneRecord(string zoneName, DnsRecord record) { try { if (record.RecordType == DnsRecordType.A) AddARecord(zoneName, record.RecordName, record.RecordData); else if (record.RecordType == DnsRecordType.AAAA) AddAAAARecord(zoneName, record.RecordName, record.RecordData); else if (record.RecordType == DnsRecordType.CNAME) AddCNameRecord(zoneName, record.RecordName, record.RecordData); else if (record.RecordType == DnsRecordType.MX) AddMXRecord(zoneName, record.RecordName, record.RecordData, record.MxPriority); else if (record.RecordType == DnsRecordType.NS) AddNsRecord(zoneName, record.RecordName, record.RecordData); else if (record.RecordType == DnsRecordType.TXT) AddTxtRecord(zoneName, record.RecordName, record.RecordData); } catch (Exception ex) { // log exception Log.WriteError( String.Format( "Simple DNS: Unable to create record (Name '{0}', Data '{1}', Text '{2}') to zone '{3}'" , record.RecordName , record.RecordData , record.RecordText , zoneName ) , ex ); } } public virtual void AddZoneRecords(string zoneName, DnsRecord[] records) { foreach (DnsRecord record in records) AddZoneRecord(zoneName, record); } public virtual void DeleteZoneRecord(string zoneName, DnsRecord record) { try { if (record.RecordType == DnsRecordType.A || record.RecordType == DnsRecordType.AAAA || record.RecordType == DnsRecordType.CNAME) record.RecordName = CorrectRecordName(zoneName, record.RecordName); // delete record DeleteRecord(zoneName, record.RecordType, record.RecordName, record.RecordData); } catch (Exception ex) { // log exception Log.WriteError( String.Format( "Simple DNS: Unable to delete record (Name '{0}', Data '{1}', Text '{2}') to zone '{3}'" , record.RecordName , record.RecordData , record.RecordText , zoneName ) , ex ); } } public virtual void DeleteZoneRecords(string zoneName, DnsRecord[] records) { foreach (DnsRecord record in records) DeleteZoneRecord(zoneName, record); } #endregion #region A & AAAA records private void AddARecord(string zoneName, string host, string ip) { // get all zone records List<DnsRecord> records = GetZoneRecordsArrayList(zoneName); // delete A record //DeleteARecordInternal(records, zoneName, host); //check if user tries to add existent zone record foreach (DnsRecord dnsRecord in records) { if ((String.Compare(dnsRecord.RecordName, host, StringComparison.OrdinalIgnoreCase) == 0) && (String.Compare(dnsRecord.RecordData, ip, StringComparison.OrdinalIgnoreCase) == 0) ) return; } // add new A record DnsRecord record = new DnsRecord(); record.RecordType = DnsRecordType.A; record.RecordName = host; record.RecordData = ip; records.Add(record); // update zone UpdateZone(zoneName, records); } private void AddAAAARecord(string zoneName, string host, string ip) { // get all zone records List<DnsRecord> records = GetZoneRecordsArrayList(zoneName); // delete AAAA record //DeleteARecordInternal(records, zoneName, host); //check if user tries to add existent zone record foreach (DnsRecord dnsRecord in records) { if ((String.Compare(dnsRecord.RecordName, host, StringComparison.OrdinalIgnoreCase) == 0) && (String.Compare(dnsRecord.RecordData, ip, StringComparison.OrdinalIgnoreCase) == 0) ) return; } // add new AAAA record DnsRecord record = new DnsRecord(); record.RecordType = DnsRecordType.AAAA; record.RecordName = host; record.RecordData = ip; records.Add(record); // update zone UpdateZone(zoneName, records); } private void DeleteRecord(string zoneName, DnsRecordType recordType, string recordName, string recordData) { // get all zone records List<DnsRecord> records = GetZoneRecordsArrayList(zoneName); // delete record DeleteRecord(zoneName, records, recordType, recordName, recordData); // update zone UpdateZone(zoneName, records); } private void DeleteRecord(string zoneName, List<DnsRecord> records, DnsRecordType recordType, string recordName, string recordData) { // delete record from the array int i = 0; while (i < records.Count) { if (records[i].RecordType == recordType && (recordName == null || String.Compare(records[i].RecordName, recordName, true) == 0) && (recordData == null || String.Compare(records[i].RecordData, recordData, true) == 0)) { records.RemoveAt(i); break; } i++; } } #endregion #region NS records private void AddNsRecord(string zoneName, string host, string nameServer) { // get all zone records List<DnsRecord> records = GetZoneRecordsArrayList(zoneName); // delete NS record //DeleteNsRecordInternal(records, zoneName, nameServer); //check if user tries to add existent zone record foreach (DnsRecord dnsRecord in records) { if ((String.Compare(dnsRecord.RecordName, host, StringComparison.OrdinalIgnoreCase) == 0) && (String.Compare(dnsRecord.RecordData, nameServer, StringComparison.OrdinalIgnoreCase) == 0)) return; } // add new NS record DnsRecord record = new DnsRecord(); record.RecordType = DnsRecordType.NS; record.RecordName = host; record.RecordData = nameServer; records.Add(record); // update zone UpdateZone(zoneName, records); } #endregion #region MX records private void AddMXRecord(string zoneName, string host, string mailServer, int mailServerPriority) { // get all zone records List<DnsRecord> records = GetZoneRecordsArrayList(zoneName); // delete MX record //DeleteMXRecordInternal(records, zoneName, mailServer); //check if user tries to add existent zone record foreach (DnsRecord dnsRecord in records) { if ((dnsRecord.RecordType == DnsRecordType.MX) && (String.Compare(dnsRecord.RecordName, host, StringComparison.OrdinalIgnoreCase) == 0) && (String.Compare(dnsRecord.RecordData, mailServer, StringComparison.OrdinalIgnoreCase) == 0) && dnsRecord.MxPriority == mailServerPriority) return; } // add new MX record DnsRecord record = new DnsRecord(); record.RecordType = DnsRecordType.MX; record.RecordName = host; record.MxPriority = mailServerPriority; record.RecordData = mailServer; records.Add(record); // update zone UpdateZone(zoneName, records); } #endregion #region CNAME records private void AddCNameRecord(string zoneName, string alias, string targetHost) { // get all zone records List<DnsRecord> records = GetZoneRecordsArrayList(zoneName); // Find existing CNAME record. This is needed in order not to have two records after web-site is created. // - verify if this record already exists... if so, we update is, otherwise create a new one DnsRecord record = records.Find( delegate(DnsRecord r) { bool isSameRecord = (r.RecordType == DnsRecordType.CNAME) && (String.Compare(r.RecordName, alias, StringComparison.OrdinalIgnoreCase) == 0); if (isSameRecord) { return true; } return false; } ); // - if no existing records were found - add one :) if (record == null) { // add new CNAME record record = new DnsRecord(); record.RecordType = DnsRecordType.CNAME; record.RecordName = alias; records.Add(record); } record.RecordData = targetHost; // update zone UpdateZone(zoneName, records); } #endregion #region TXT records private void AddTxtRecord(string zoneName, string host, string text) { // get all zone records List<DnsRecord> records = GetZoneRecordsArrayList(zoneName); // delete TXT record //DeleteTxtRecordInternal(records, zoneName, text); //check if user tries to add existent zone record foreach (DnsRecord dnsRecord in records) { if ((String.Compare(dnsRecord.RecordName, host, StringComparison.OrdinalIgnoreCase) == 0) && (String.Compare(dnsRecord.RecordData, text, StringComparison.OrdinalIgnoreCase) == 0)) return; } // add new TXT record DnsRecord record = new DnsRecord(); record.RecordType = DnsRecordType.TXT; record.RecordName = host; record.RecordData = text; records.Add(record); // update zone UpdateZone(zoneName, records); } #endregion #region SOA record public virtual void UpdateSoaRecord(string zoneName, string host, string primaryNsServer, string primaryPerson) { // get all zone records List<DnsRecord> records = GetZoneRecordsArrayList(zoneName); // delete SOA record DeleteRecord(zoneName, records, DnsRecordType.SOA, null, null); // add new TXT record DnsSOARecord soa = new DnsSOARecord(); soa.RecordType = DnsRecordType.SOA; soa.RecordName = ""; soa.PrimaryNsServer = primaryNsServer; soa.PrimaryPerson = primaryPerson; records.Add(soa); // update primary person contact //if (soa.PrimaryPerson.ToLower().EndsWith(zoneName.ToLower())) // soa.PrimaryPerson = soa.PrimaryPerson.Substring(0, (soa.PrimaryPerson.Length - zoneName.Length) - 1); // update zone UpdateZone(zoneName, records); } #endregion #region IHostingServiceProvier methods public override void DeleteServiceItems(ServiceProviderItem[] items) { foreach (ServiceProviderItem item in items) { if (item is DnsZone) { try { // delete DNS zone DeleteZone(item.Name); } catch (Exception ex) { Log.WriteError(String.Format("Error deleting '{0}' SimpleDNS zone", item.Name), ex); } } } } #endregion #region Protected methods protected virtual DnsRecord[] ParseZoneFile(string zoneName, string zf) { return ParseZoneFileToArrayList(zoneName, zf).ToArray(); } protected virtual List<DnsRecord> ParseZoneFileToArrayList(string zoneName, string zf) { List<DnsRecord> records = new List<DnsRecord>(); StringReader reader = new StringReader(zf); string zfLine = null; DnsSOARecord soa = null; while ((zfLine = reader.ReadLine()) != null) { //string line = Regex.Replace(zfLine, "\\s+", " ").Trim(); string[] columns = zfLine.Split('\t'); string recordName = ""; string recordTTL = ""; string recordType = ""; string recordData = ""; string recordData2 = ""; recordName = columns[0]; if (columns.Length > 1) recordTTL = columns[1]; if (columns.Length > 2) recordType = columns[2]; if (columns.Length > 3) recordData = columns[3]; if (columns.Length > 4) recordData2 = columns[4].Trim(); if (recordType == "IN SOA") { string[] dataColumns = recordData.Split(' '); // parse SOA record soa = new DnsSOARecord(); soa.RecordType = DnsRecordType.SOA; soa.RecordName = ""; soa.PrimaryNsServer = RemoveTrailingDot(dataColumns[0]); soa.PrimaryPerson = RemoveTrailingDot(dataColumns[1]); soa.RecordText = zfLine; if (dataColumns[2] != "(") soa.SerialNumber = dataColumns[2]; // add to the collection records.Add(soa); } else if (recordData2.IndexOf("; Serial number") != -1) { string[] dataColumns = recordData2.Split(' '); // append soa serial number soa.SerialNumber = dataColumns[0]; } else if (recordType == "NS") // NS record with empty host { DnsRecord r = new DnsRecord(); r.RecordType = DnsRecordType.NS; r.RecordName = CorrectRecordName(zoneName, recordName); r.RecordData = CorrectRecordData(zoneName, recordData); r.RecordText = zfLine; records.Add(r); } else if (recordType == "A") // A record { DnsRecord r = new DnsRecord(); r.RecordType = DnsRecordType.A; r.RecordName = CorrectRecordName(zoneName, recordName); r.RecordData = recordData; r.RecordText = zfLine; records.Add(r); } else if (recordType == "AAAA") // A record { DnsRecord r = new DnsRecord(); r.RecordType = DnsRecordType.AAAA; r.RecordName = CorrectRecordName(zoneName, recordName); r.RecordData = recordData; r.RecordText = zfLine; records.Add(r); } else if (recordType == "CNAME") // CNAME record { DnsRecord r = new DnsRecord(); r.RecordType = DnsRecordType.CNAME; r.RecordName = CorrectRecordName(zoneName, recordName); r.RecordData = CorrectRecordData(zoneName, recordData, recordData); r.RecordText = zfLine; records.Add(r); } else if (recordType == "MX") // MX record { string[] dataColumns = recordData.Split(' '); DnsRecord r = new DnsRecord(); r.RecordType = DnsRecordType.MX; r.RecordName = CorrectRecordName(zoneName, recordName); r.MxPriority = Int32.Parse(dataColumns[0]); r.RecordData = CorrectRecordData(zoneName, dataColumns[1]); r.RecordText = zfLine; records.Add(r); } else if (recordType == "TXT") // TXT record { DnsRecord r = new DnsRecord(); r.RecordType = DnsRecordType.TXT; r.RecordName = CorrectRecordName(zoneName, recordName); r.RecordData = recordData.Substring(1, recordData.Length - 2); r.RecordText = zfLine; records.Add(r); } else if (zfLine.StartsWith(";$AllowZT") || zfLine.StartsWith(";$PrimaryIP") || zfLine.StartsWith(";$MinimumTTL")) { // unknown record just keep it line DnsRecord r = new DnsRecord(); r.RecordType = DnsRecordType.Other; r.RecordName = ""; r.RecordText = zfLine; records.Add(r); } //Debug.WriteLine(zfLine); } return records; } protected virtual void UpdateZone(string zoneName, List<DnsRecord> records) { UpdateZone(zoneName, records, null); } protected virtual void UpdateZone(string zoneName, List<DnsRecord> records, string[] masterServers) { // build zone file StringBuilder sb = new StringBuilder(); // add WebsitePanel comment sb.Append(";$; Updated with WebsitePanel DNS API ").Append(DateTime.Now).Append("\r"); // render comment/service records foreach (DnsRecord rr in records) { if (rr.RecordText != null && rr.RecordText.StartsWith(";") && !(rr.RecordType == DnsRecordType.TXT)) { sb.Append(rr.RecordText); // add line break sb.Append("\r"); } } // render SOA record foreach (DnsRecord rr in records) { string host = ""; string type = ""; string data = ""; if (rr is DnsSOARecord) { type = "IN SOA"; DnsSOARecord soa = (DnsSOARecord)rr; host = soa.RecordName; data = String.Format("{0} {1} {2} {3} {4} {5} {6}", CorrectSOARecord(zoneName, soa.PrimaryNsServer), CorrectSOARecord(zoneName, soa.PrimaryPerson), UpdateSerialNumber(soa.SerialNumber), RefreshInterval, RetryDelay, ExpireLimit, MinimumTTL); // add line to the zone file sb.Append(BuildRecordName(zoneName, host)).Append("\t"); sb.Append("\t"); sb.Append(type).Append("\t"); sb.Append(data); // add line break sb.Append("\r"); } } // render all other records foreach (DnsRecord rr in records) { string host = String.Empty; string type = String.Empty; string data = String.Empty; string name = String.Empty; if (rr.RecordType == DnsRecordType.A) { type = "A"; host = rr.RecordName; data = rr.RecordData; name = BuildRecordName(zoneName, host); } else if (rr.RecordType == DnsRecordType.AAAA) { type = "AAAA"; host = rr.RecordName; data = rr.RecordData; name = BuildRecordName(zoneName, host); } else if (rr.RecordType == DnsRecordType.NS) { type = "NS"; host = rr.RecordName; data = BuildRecordData(zoneName, rr.RecordData); name = BuildRecordName(zoneName, host); } else if (rr.RecordType == DnsRecordType.CNAME) { type = "CNAME"; host = rr.RecordName; data = BuildRecordData(zoneName, rr.RecordData, rr.RecordData); name = host; } else if (rr.RecordType == DnsRecordType.MX) { type = "MX"; host = rr.RecordName; data = String.Format("{0} {1}", rr.MxPriority, BuildRecordData(zoneName, rr.RecordData)); name = BuildRecordName(zoneName, host); } else if (rr.RecordType == DnsRecordType.TXT) { type = "TXT"; host = rr.RecordName; data = "\"" + rr.RecordData + "\""; name = BuildRecordName(zoneName, host); } // add line to the zone file if (type != "") { sb.Append(name).Append("\t"); if (type == "NS") sb.Append(MinimumTTL); sb.Append("\t"); sb.Append(type).Append("\t"); sb.Append(data); // add line break sb.Append("\r"); } } string zoneFile = sb.ToString(); // update zone file string queryParams = "zone=" + zoneName + "&data=" + zoneFile; if (masterServers != null && masterServers.Length > 0) queryParams += "&masterip=" + masterServers[0]; // execute query string result = ExecuteDnsQuery("updatezone", queryParams); } #endregion #region private methods private string CorrectRecordName(string zoneName, string host) { if (host == "" || host == "@") return ""; else if (host.EndsWith(".")) return RemoveTrailingDot(host); else return host; } private string CorrectRecordData(string zoneName, string host, string recordData) { if (recordData == "@") { return zoneName; } return CorrectRecordData(zoneName, host); } private string CorrectRecordData(string zoneName, string host) { if (host == "" || host == "@") return ""; else if (host.EndsWith(".")) return RemoveTrailingDot(host); else return host + "." + zoneName; } protected string BuildRecordName(string zoneName, string host) { if (host == "") return "@"; else if (host.EndsWith(zoneName)) return host.Substring(0, host.Length - zoneName.Length - 1); else return host; } protected string BuildRecordData(string zoneName, string host, string recordData) { if (String.Compare(zoneName, recordData, StringComparison.OrdinalIgnoreCase) == 0) { return "@"; } return BuildRecordData(zoneName, host); } protected string BuildRecordData(string zoneName, string host) { try { if (host == "") return "@"; else if (host.EndsWith("." + zoneName)) return host.Substring(0, host.Length - zoneName.Length - 1); else return host + "."; } catch (ArgumentOutOfRangeException ex) { Log.WriteError( String.Format( "Simple DNS: Cannot build record data. Zone name: {0}, Host {1}." , zoneName , host ) , ex ); throw ex; } } protected string CorrectSOARecord(string zoneName, string data) { if (data == "") return "@"; else if (data.EndsWith("." + zoneName)) return data.Substring(0, data.Length - zoneName.Length - 1); else if (data.IndexOf(".") == -1) return data; else return data + "."; } protected string UpdateSerialNumber(string serialNumber) { // update record's serial number string sn = serialNumber; string todayDate = DateTime.Now.ToString("yyyyMMdd"); if (sn == null || sn.Length < 10 || !sn.StartsWith(todayDate)) { // build a new serial number return todayDate + "01"; } else { // just increment serial number int newSerialNumber = Int32.Parse(serialNumber); newSerialNumber += 1; return newSerialNumber.ToString(); } } private string RemoveTrailingDot(string str) { if (str.Length == 0 || str[str.Length - 1] != '.') return str; else return str.Substring(0, str.Length - 1); } private string ExecuteDnsQuery(string command, string postData) { HttpWebResponse result = null; StringBuilder sb = new StringBuilder(); try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(SimpleDnsUrl + "/" + command); req.Method = (postData == null) ? "GET" : "POST"; req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705)"; req.ContentType = "application/x-www-form-urlencoded"; if (!String.IsNullOrEmpty(SimpleDnsPassword)) { CredentialCache myCache = new CredentialCache(); myCache.Add(new Uri(SimpleDnsUrl + "/" + command), "Basic", new NetworkCredential(AdminLogin, SimpleDnsPassword)); req.Credentials = myCache; } StringBuilder UrlEncoded = new StringBuilder(); Char[] reserved = { '?', '=', '&' }; byte[] SomeBytes = null; if (postData != null) { int i = 0, j; while (i < postData.Length) { j = postData.IndexOfAny(reserved, i); if (j == -1) { UrlEncoded.Append(HttpUtility.UrlEncode(postData.Substring(i, postData.Length - i))); break; } UrlEncoded.Append(HttpUtility.UrlEncode(postData.Substring(i, j - i))); UrlEncoded.Append(postData.Substring(j, 1)); i = j + 1; } SomeBytes = Encoding.ASCII.GetBytes(UrlEncoded.ToString()); req.ContentLength = SomeBytes.Length; Stream newStream = req.GetRequestStream(); newStream.Write(SomeBytes, 0, SomeBytes.Length); newStream.Close(); } // load document result = (HttpWebResponse)req.GetResponse(); Stream ReceiveStream = result.GetResponseStream(); Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); StreamReader sr = new StreamReader(ReceiveStream, encode); //Console.WriteLine("\r\nResponse stream received"); Char[] read = new Char[256]; int count = sr.Read(read, 0, 256); //Console.WriteLine("HTML...\r\n"); while (count > 0) { String str = new String(read, 0, count); sb.Append(str); count = sr.Read(read, 0, 256); } } //catch (WebException ex) //{ // response.Status = -1; // HttpWebResponse errorResp = (HttpWebResponse)ex.Response; // if (errorResp != null) // { // response.Status = (int)errorResp.StatusCode; // } // response.Content = ex.Status.ToString(); // return response; //} //catch (Exception ex) //{ // //Debug.WriteLine(ex); // response.Status = -1; // response.Content = ex.ToString(); // return response; //} finally { if (result != null) { result.Close(); } } return sb.ToString(); } #endregion public override bool IsInstalled() { string productName = null; string productVersion = null; RegistryKey HKLM = Registry.LocalMachine; RegistryKey key = HKLM.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"); if (key != null) { String[] names = key.GetSubKeyNames(); foreach (string s in names) { RegistryKey subkey = HKLM.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" + s); if (subkey != null) if (!String.IsNullOrEmpty((string)subkey.GetValue("DisplayName"))) { productName = (string)subkey.GetValue("DisplayName"); } if (productName != null) if (productName.Equals("Simple DNS Plus")) { if (subkey != null) productVersion = (string)subkey.GetValue("DisplayVersion"); break; } } if (!String.IsNullOrEmpty(productVersion)) { string[] split = productVersion.Split(new char[] { '.' }); return split[0].Equals("4"); } //checking x64 platform key = HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"); if (key == null) { return false; } names = key.GetSubKeyNames(); foreach (string s in names) { RegistryKey subkey = HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\" + s); if (subkey != null) if (!String.IsNullOrEmpty((string)subkey.GetValue("DisplayName"))) { productName = (string)subkey.GetValue("DisplayName"); } if (productName != null) if (productName.Equals("Simple DNS Plus")) { if (subkey != null) productVersion = (string)subkey.GetValue("DisplayVersion"); break; } } if (!String.IsNullOrEmpty(productVersion)) { string[] split = productVersion.Split(new[] { '.' }); return split[0].Equals("4"); } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; using TestLibrary; /// <summary> /// UInt64.ToString(System.IFormatProvider) /// </summary> public class UInt64ToString1 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); if (Utilities.IsWindows) { // retVal = NegTest1() && retVal; // Disabled until neutral cultures are available } return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Convert UInt64MaxValue to string value and using cultureinfo \"en-US\""); try { UInt64 u64 = UInt64.MaxValue; CultureInfo cultureInfo = new CultureInfo("en-US"); string str = u64.ToString(cultureInfo); if (str != "18446744073709551615") { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Convert UInt64MinValue to string value and using cultureinfo \"fr-FR\""); try { UInt64 u64 = UInt64.MinValue; CultureInfo cultureInfo = new CultureInfo("fr-FR"); string str = u64.ToString(cultureInfo); if (str != "0") { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: A UInt64 number begin with zeros and using cultureinfo \"en-US\""); try { UInt64 u64 = 00009876; CultureInfo cultureInfo = new CultureInfo("en-US"); string str = u64.ToString(cultureInfo); if (str != "9876") { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Convert a random uint64 to string value and using \"en-GB\""); try { UInt64 u64 = this.GetInt64(0, UInt64.MaxValue); CultureInfo cultureInfo = new CultureInfo("en-GB"); string str = u64.ToString(cultureInfo); string str2 = Convert.ToString(u64); if (str != str2) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: The provider is a null reference"); try { UInt64 u64 = 000217639083000; CultureInfo cultureInfo = null; string str = u64.ToString(cultureInfo); if (str != "217639083000") { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The provider argument is invalid"); try { UInt64 u64 = 1234500233; CultureInfo cultureInfo = new CultureInfo("pl"); string str = u64.ToString(cultureInfo); TestLibrary.TestFramework.LogError("101", "The NotSupportedException is not thrown as expected"); retVal = false; } catch (NotSupportedException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { UInt64ToString1 test = new UInt64ToString1(); TestLibrary.TestFramework.BeginTestCase("UInt64ToString1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region ForTestObject private UInt64 GetInt64(UInt64 minValue, UInt64 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + (UInt64)TestLibrary.Generator.GetInt64(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
using System; using System.Collections; using System.Collections.Generic; using System.IO.Pipelines; using System.IO.Pipelines.Text.Primitives; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; namespace SocketServer { public class RequestHeaderDictionary : IHeaderDictionary { private static readonly byte[] ContentLengthKeyBytes = Encoding.ASCII.GetBytes("CONTENT-LENGTH"); private static readonly byte[] ContentTypeKeyBytes = Encoding.ASCII.GetBytes("CONTENT-TYPE"); private static readonly byte[] AcceptBytes = Encoding.ASCII.GetBytes("ACCEPT"); private static readonly byte[] AcceptLanguageBytes = Encoding.ASCII.GetBytes("ACCEPT-LANGUAGE"); private static readonly byte[] AcceptEncodingBytes = Encoding.ASCII.GetBytes("ACCEPT-ENCODING"); private static readonly byte[] HostBytes = Encoding.ASCII.GetBytes("HOST"); private static readonly byte[] ConnectionBytes = Encoding.ASCII.GetBytes("CONNECTION"); private static readonly byte[] CacheControlBytes = Encoding.ASCII.GetBytes("CACHE-CONTROL"); private static readonly byte[] UserAgentBytes = Encoding.ASCII.GetBytes("USER-AGENT"); private static readonly byte[] UpgradeInsecureRequests = Encoding.ASCII.GetBytes("UPGRADE-INSECURE-REQUESTS"); private Dictionary<string, HeaderValue> _headers = new Dictionary<string, HeaderValue>(10, StringComparer.OrdinalIgnoreCase); public StringValues this[string key] { get { TryGetValue(key, out var values); return values; } set => SetHeader(key, value); } public int Count => _headers.Count; public bool IsReadOnly => false; public ICollection<string> Keys => _headers.Keys; public ICollection<StringValues> Values => _headers.Values.Select(v => v.GetValue()).ToList(); public long? ContentLength { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public void SetHeader(ref ReadableBuffer key, ref ReadableBuffer value) { var headerKey = GetHeaderKey(ref key); _headers[headerKey] = new HeaderValue { Raw = value.Preserve() }; } public ReadableBuffer GetHeaderRaw(string key) { if (_headers.TryGetValue(key, out var value)) { return value.Raw.Value.Buffer; } return default(ReadableBuffer); } private string GetHeaderKey(ref ReadableBuffer key) { // Uppercase the things foreach (var memory in key) { var data = memory.Span; for (var i = 0; i < memory.Length; i++) { var mask = IsAlpha(data[i]) ? 0xdf : 0xff; data[i] = (byte)(data[i] & mask); } } if (EqualsIgnoreCase(ref key, AcceptBytes)) { return "Accept"; } if (EqualsIgnoreCase(ref key, AcceptEncodingBytes)) { return "Accept-Encoding"; } if (EqualsIgnoreCase(ref key, AcceptLanguageBytes)) { return "Accept-Language"; } if (EqualsIgnoreCase(ref key, HostBytes)) { return "Host"; } if (EqualsIgnoreCase(ref key, UserAgentBytes)) { return "User-Agent"; } if (EqualsIgnoreCase(ref key, CacheControlBytes)) { return "Cache-Control"; } if (EqualsIgnoreCase(ref key, ConnectionBytes)) { return "Connection"; } if (EqualsIgnoreCase(ref key, UpgradeInsecureRequests)) { return "Upgrade-Insecure-Requests"; } return key.GetAsciiString(); } private bool EqualsIgnoreCase(ref ReadableBuffer key, byte[] buffer) { if (key.Length != buffer.Length) { return false; } return key.EqualsTo(buffer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsAlpha(byte b) => b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z'; private void SetHeader(string key, StringValues value) => _headers[key] = new HeaderValue { Value = value }; public void Add(KeyValuePair<string, StringValues> item) => SetHeader(item.Key, item.Value); public void Add(string key, StringValues value) => SetHeader(key, value); public void Clear() => _headers.Clear(); public bool Contains(KeyValuePair<string, StringValues> item) => false; public bool ContainsKey(string key) => _headers.ContainsKey(key); public void CopyTo(KeyValuePair<string, StringValues>[] array, int arrayIndex) => throw new NotSupportedException(); public void Reset() { foreach (var pair in _headers) { pair.Value.Raw?.Dispose(); } _headers.Clear(); } public IEnumerator<KeyValuePair<string, StringValues>> GetEnumerator() => _headers.Select(h => new KeyValuePair<string, StringValues>(h.Key, h.Value.GetValue())).GetEnumerator(); public bool Remove(KeyValuePair<string, StringValues> item) => throw new NotImplementedException(); public bool Remove(string key) => _headers.Remove(key); public bool TryGetValue(string key, out StringValues value) { if (_headers.TryGetValue(key, out var headerValue)) { value = headerValue.GetValue(); return true; } return false; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); private struct HeaderValue { public PreservedBuffer? Raw; public StringValues? Value; public StringValues GetValue() { if (!Value.HasValue) { if (!Raw.HasValue) { return StringValues.Empty; } Value = Raw.Value.Buffer.GetAsciiString(); } return Value.Value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Batgai.Input { class GetInput { private KeyboardState oldKeyState; private GamePadState oldPadState; private PlayerIndex playerIndex; float movementSpeed = 10.0f; bool backPressed = false; bool actionPressed = false; bool actionReleased = false; int actionFramesHeld = 0; bool upPressed = false; bool leftPressed = false; bool downPressed = false; bool rightPressed = false; bool[] directionBoolArray; bool isDirectionArrayEmpty = true; Vector2 directionPressed = new Vector2(0, 0); //Delegates public delegate void buttonPressDelegate(); public delegate void buttonHeldDelegate(int framesHeld); public delegate void directionBoolDelegate(bool[] directionArray); public delegate void directionPressDelegate(Vector2 value); //Events public event buttonPressDelegate event_actionPressed; public event buttonHeldDelegate event_actionHeld; public event buttonPressDelegate event_actionReleased; public event buttonPressDelegate event_backPressed; public event directionBoolDelegate event_directionBoolPressed; public event directionPressDelegate event_directionPressed; public GetInput(PlayerIndex index) { playerIndex = index; directionBoolArray = new bool[4] { upPressed, leftPressed, downPressed, rightPressed }; oldKeyState = Keyboard.GetState(); oldPadState = GamePad.GetState(playerIndex); } public void update(GameTime gameTime) { backPressed = false; actionPressed = false; actionReleased = false; isDirectionArrayEmpty = true; for (int i = 0; i < 4; i++) { directionBoolArray[i] = false; } directionPressed = Vector2.Zero; #region keyboardInput if (oldKeyState != Keyboard.GetState()) { if (Keyboard.GetState().IsKeyDown(Keys.Escape)) { backPressed = true; } else if (Keyboard.GetState().IsKeyDown(Keys.Space)) { actionPressed = true; } if (Keyboard.GetState().IsKeyDown(Keys.W)) { directionBoolArray[0] = true; isDirectionArrayEmpty = false; } if (Keyboard.GetState().IsKeyDown(Keys.A)) { directionBoolArray[1] = true; isDirectionArrayEmpty = false; } if (Keyboard.GetState().IsKeyDown(Keys.S)) { directionBoolArray[2] = true; isDirectionArrayEmpty = false; } if (Keyboard.GetState().IsKeyDown(Keys.D)) { directionBoolArray[3] = true; isDirectionArrayEmpty = false; } } if (actionFramesHeld > 0 && Keyboard.GetState().IsKeyUp(Keys.Space) && GamePad.GetState(playerIndex).IsButtonUp(Buttons.A)) { actionReleased = true; } if (Keyboard.GetState().IsKeyDown(Keys.Space) || GamePad.GetState(playerIndex).IsButtonDown(Buttons.A)) //sad but necessary { actionFramesHeld++; } else { actionFramesHeld = 0; } if (Keyboard.GetState().IsKeyDown(Keys.W)) { directionPressed.Y = -movementSpeed; } else if (Keyboard.GetState().IsKeyDown(Keys.S)) { directionPressed.Y = movementSpeed; } if (Keyboard.GetState().IsKeyDown(Keys.A)) { directionPressed.X = -movementSpeed; } else if (Keyboard.GetState().IsKeyDown(Keys.D)) { directionPressed.X = movementSpeed; } oldKeyState = Keyboard.GetState(); #endregion #region xbox if (oldPadState != GamePad.GetState(playerIndex)) { if (GamePad.GetState(playerIndex).IsButtonDown(Buttons.Start)) { backPressed = true; } if (GamePad.GetState(playerIndex).IsButtonDown(Buttons.A)) { actionPressed = true; } if (GamePad.GetState(playerIndex).DPad.Up == ButtonState.Pressed) { directionBoolArray[0] = true; isDirectionArrayEmpty = false; } if (GamePad.GetState(playerIndex).DPad.Left == ButtonState.Pressed) { directionBoolArray[1] = true; isDirectionArrayEmpty = false; } if (GamePad.GetState(playerIndex).DPad.Down == ButtonState.Pressed) { directionBoolArray[2] = true; isDirectionArrayEmpty = false; } if (GamePad.GetState(playerIndex).DPad.Right == ButtonState.Pressed) { directionBoolArray[3] = true; isDirectionArrayEmpty = false; } } if (actionFramesHeld > 0 && GamePad.GetState(playerIndex).IsButtonUp(Buttons.A) && Keyboard.GetState().IsKeyUp(Keys.Space)) { actionReleased = true; } if (GamePad.GetState(playerIndex).ThumbSticks.Left.X != 0 || GamePad.GetState(playerIndex).ThumbSticks.Left.Y != 0) { directionPressed.X = GamePad.GetState(playerIndex).ThumbSticks.Left.X * movementSpeed; directionPressed.Y = -GamePad.GetState(playerIndex).ThumbSticks.Left.Y * movementSpeed; } oldPadState = GamePad.GetState(playerIndex); #endregion #region events if (actionPressed && event_actionPressed != null) { event_actionPressed(); } if (backPressed && event_backPressed != null) { event_backPressed(); } if (!isDirectionArrayEmpty && event_directionBoolPressed != null) { event_directionBoolPressed(directionBoolArray); } if (directionPressed != Vector2.Zero && event_directionPressed != null) { event_directionPressed(directionPressed); } if (actionReleased && event_actionReleased != null) { event_actionReleased(); } if (actionFramesHeld > 0 && event_actionHeld != null) { event_actionHeld(actionFramesHeld); } #endregion } } }
/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.IsolatedStorage; using System.Runtime.Serialization; using System.Security; using System.Text; using System.Windows; using System.Windows.Resources; namespace WPCordovaClassLib.Cordova.Commands { /// <summary> /// Provides access to isolated storage /// </summary> public class File : BaseCommand { // Error codes public const int NOT_FOUND_ERR = 1; public const int SECURITY_ERR = 2; public const int ABORT_ERR = 3; public const int NOT_READABLE_ERR = 4; public const int ENCODING_ERR = 5; public const int NO_MODIFICATION_ALLOWED_ERR = 6; public const int INVALID_STATE_ERR = 7; public const int SYNTAX_ERR = 8; public const int INVALID_MODIFICATION_ERR = 9; public const int QUOTA_EXCEEDED_ERR = 10; public const int TYPE_MISMATCH_ERR = 11; public const int PATH_EXISTS_ERR = 12; // File system options public const int TEMPORARY = 0; public const int PERSISTENT = 1; public const int RESOURCE = 2; public const int APPLICATION = 3; /// <summary> /// Temporary directory name /// </summary> private readonly string TMP_DIRECTORY_NAME = "tmp"; /// <summary> /// Represents error code for callback /// </summary> [DataContract] public class ErrorCode { /// <summary> /// Error code /// </summary> [DataMember(IsRequired = true, Name = "code")] public int Code { get; set; } /// <summary> /// Creates ErrorCode object /// </summary> public ErrorCode(int code) { this.Code = code; } } /// <summary> /// Represents File action options. /// </summary> [DataContract] public class FileOptions { /// <summary> /// File path /// </summary> /// private string _fileName; [DataMember(Name = "fileName")] public string FilePath { get { return this._fileName; } set { int index = value.IndexOfAny(new char[] { '#', '?' }); this._fileName = index > -1 ? value.Substring(0, index) : value; } } /// <summary> /// Full entryPath /// </summary> [DataMember(Name = "fullPath")] public string FullPath { get; set; } /// <summary> /// Directory name /// </summary> [DataMember(Name = "dirName")] public string DirectoryName { get; set; } /// <summary> /// Path to create file/directory /// </summary> [DataMember(Name = "path")] public string Path { get; set; } /// <summary> /// The encoding to use to encode the file's content. Default is UTF8. /// </summary> [DataMember(Name = "encoding")] public string Encoding { get; set; } /// <summary> /// Uri to get file /// </summary> /// private string _uri; [DataMember(Name = "uri")] public string Uri { get { return this._uri; } set { int index = value.IndexOfAny(new char[] { '#', '?' }); this._uri = index > -1 ? value.Substring(0, index) : value; } } /// <summary> /// Size to truncate file /// </summary> [DataMember(Name = "size")] public long Size { get; set; } /// <summary> /// Data to write in file /// </summary> [DataMember(Name = "data")] public string Data { get; set; } /// <summary> /// Position the writing starts with /// </summary> [DataMember(Name = "position")] public int Position { get; set; } /// <summary> /// Type of file system requested /// </summary> [DataMember(Name = "type")] public int FileSystemType { get; set; } /// <summary> /// New file/directory name /// </summary> [DataMember(Name = "newName")] public string NewName { get; set; } /// <summary> /// Destination directory to copy/move file/directory /// </summary> [DataMember(Name = "parent")] public string Parent { get; set; } /// <summary> /// Options for getFile/getDirectory methods /// </summary> [DataMember(Name = "options")] public CreatingOptions CreatingOpt { get; set; } /// <summary> /// Creates options object with default parameters /// </summary> public FileOptions() { this.SetDefaultValues(new StreamingContext()); } /// <summary> /// Initializes default values for class fields. /// Implemented in separate method because default constructor is not invoked during deserialization. /// </summary> /// <param name="context"></param> [OnDeserializing()] public void SetDefaultValues(StreamingContext context) { this.Encoding = "UTF-8"; this.FilePath = ""; this.FileSystemType = -1; } } /// <summary> /// Stores image info /// </summary> [DataContract] public class FileMetadata { [DataMember(Name = "fileName")] public string FileName { get; set; } [DataMember(Name = "fullPath")] public string FullPath { get; set; } [DataMember(Name = "type")] public string Type { get; set; } [DataMember(Name = "lastModifiedDate")] public string LastModifiedDate { get; set; } [DataMember(Name = "size")] public long Size { get; set; } public FileMetadata(string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new FileNotFoundException("File doesn't exist"); } this.FullPath = filePath; this.Size = 0; this.FileName = string.Empty; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { bool IsFile = isoFile.FileExists(filePath); bool IsDirectory = isoFile.DirectoryExists(filePath); if (!IsDirectory) { if (!IsFile) // special case, if isoFile cannot find it, it might still be part of the app-package { // attempt to get it from the resources Uri fileUri = new Uri(filePath, UriKind.Relative); StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri); if (streamInfo != null) { this.Size = streamInfo.Stream.Length; this.FileName = filePath.Substring(filePath.LastIndexOf("/") + 1); } else { throw new FileNotFoundException("File doesn't exist"); } } else { using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.Read, isoFile)) { this.Size = stream.Length; } this.FileName = System.IO.Path.GetFileName(filePath); this.LastModifiedDate = isoFile.GetLastWriteTime(filePath).DateTime.ToString(); } } this.Type = MimeTypeMapper.GetMimeType(this.FileName); } } } /// <summary> /// Represents file or directory modification metadata /// </summary> [DataContract] public class ModificationMetadata { /// <summary> /// Modification time /// </summary> [DataMember] public string modificationTime { get; set; } } /// <summary> /// Represents file or directory entry /// </summary> [DataContract] public class FileEntry { /// <summary> /// File type /// </summary> [DataMember(Name = "isFile")] public bool IsFile { get; set; } /// <summary> /// Directory type /// </summary> [DataMember(Name = "isDirectory")] public bool IsDirectory { get; set; } /// <summary> /// File/directory name /// </summary> [DataMember(Name = "name")] public string Name { get; set; } /// <summary> /// Full path to file/directory /// </summary> [DataMember(Name = "fullPath")] public string FullPath { get; set; } public bool IsResource { get; set; } public static FileEntry GetEntry(string filePath, bool bIsRes=false) { FileEntry entry = null; try { entry = new FileEntry(filePath, bIsRes); } catch (Exception ex) { Debug.WriteLine("Exception in GetEntry for filePath :: " + filePath + " " + ex.Message); } return entry; } /// <summary> /// Creates object and sets necessary properties /// </summary> /// <param name="filePath"></param> public FileEntry(string filePath, bool bIsRes = false) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentException(); } if(filePath.Contains(" ")) { Debug.WriteLine("FilePath with spaces :: " + filePath); } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { IsResource = bIsRes; IsFile = isoFile.FileExists(filePath); IsDirectory = isoFile.DirectoryExists(filePath); if (IsFile) { this.Name = Path.GetFileName(filePath); } else if (IsDirectory) { this.Name = this.GetDirectoryName(filePath); if (string.IsNullOrEmpty(Name)) { this.Name = "/"; } } else { if (IsResource) { this.Name = Path.GetFileName(filePath); } else { throw new FileNotFoundException(); } } try { this.FullPath = filePath.Replace('\\', '/'); // new Uri(filePath).LocalPath; } catch (Exception) { this.FullPath = filePath; } } } /// <summary> /// Extracts directory name from path string /// Path should refer to a directory, for example \foo\ or /foo. /// </summary> /// <param name="path"></param> /// <returns></returns> private string GetDirectoryName(string path) { if (String.IsNullOrEmpty(path)) { return path; } string[] split = path.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); if (split.Length < 1) { return null; } else { return split[split.Length - 1]; } } } /// <summary> /// Represents info about requested file system /// </summary> [DataContract] public class FileSystemInfo { /// <summary> /// file system type /// </summary> [DataMember(Name = "name", IsRequired = true)] public string Name { get; set; } /// <summary> /// Root directory entry /// </summary> [DataMember(Name = "root", EmitDefaultValue = false)] public FileEntry Root { get; set; } /// <summary> /// Creates class instance /// </summary> /// <param name="name"></param> /// <param name="rootEntry"> Root directory</param> public FileSystemInfo(string name, FileEntry rootEntry = null) { Name = name; Root = rootEntry; } } [DataContract] public class CreatingOptions { /// <summary> /// Create file/directory if is doesn't exist /// </summary> [DataMember(Name = "create")] public bool Create { get; set; } /// <summary> /// Generate an exception if create=true and file/directory already exists /// </summary> [DataMember(Name = "exclusive")] public bool Exclusive { get; set; } } // returns null value if it fails. private string[] getOptionStrings(string options) { string[] optStings = null; try { optStings = JSON.JsonHelper.Deserialize<string[]>(options); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), CurrentCommandCallbackId); } return optStings; } /// <summary> /// Gets amount of free space available for Isolated Storage /// </summary> /// <param name="options">No options is needed for this method</param> public void getFreeDiskSpace(string options) { string callbackId = getOptionStrings(options)[0]; try { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isoFile.AvailableFreeSpace), callbackId); } } catch (IsolatedStorageException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } /// <summary> /// Check if file exists /// </summary> /// <param name="options">File path</param> public void testFileExists(string options) { IsDirectoryOrFileExist(options, false); } /// <summary> /// Check if directory exists /// </summary> /// <param name="options">directory name</param> public void testDirectoryExists(string options) { IsDirectoryOrFileExist(options, true); } /// <summary> /// Check if file or directory exist /// </summary> /// <param name="options">File path/Directory name</param> /// <param name="isDirectory">Flag to recognize what we should check</param> public void IsDirectoryOrFileExist(string options, bool isDirectory) { string[] args = getOptionStrings(options); string callbackId = args[1]; FileOptions fileOptions = JSON.JsonHelper.Deserialize<FileOptions>(args[0]); string filePath = args[0]; if (fileOptions == null) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); } try { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { bool isExist; if (isDirectory) { isExist = isoFile.DirectoryExists(fileOptions.DirectoryName); } else { isExist = isoFile.FileExists(fileOptions.FilePath); } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isExist), callbackId); } } catch (IsolatedStorageException) // default handler throws INVALID_MODIFICATION_ERR { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } public void readAsDataURL(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; int startPos = int.Parse(optStrings[1]); int endPos = int.Parse(optStrings[2]); string callbackId = optStrings[3]; if (filePath != null) { try { string base64URL = null; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string mimeType = MimeTypeMapper.GetMimeType(filePath); using (IsolatedStorageFileStream stream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read)) { string base64String = GetFileContent(stream); base64URL = "data:" + mimeType + ";base64," + base64String; } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, base64URL), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } } public void readAsArrayBuffer(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; int startPos = int.Parse(optStrings[1]); int endPos = int.Parse(optStrings[2]); string callbackId = optStrings[3]; DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), callbackId); } public void readAsBinaryString(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; int startPos = int.Parse(optStrings[1]); int endPos = int.Parse(optStrings[2]); string callbackId = optStrings[3]; DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), callbackId); } public void readAsText(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; string encStr = optStrings[1]; int startPos = int.Parse(optStrings[2]); int endPos = int.Parse(optStrings[3]); string callbackId = optStrings[4]; try { string text = ""; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(filePath)) { readResourceAsText(options); return; } Encoding encoding = Encoding.GetEncoding(encStr); using (IsolatedStorageFileStream reader = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read)) { if (startPos < 0) { startPos = Math.Max((int)reader.Length + startPos, 0); } else if (startPos > 0) { startPos = Math.Min((int)reader.Length, startPos); } if (endPos > 0) { endPos = Math.Min((int)reader.Length, endPos); } else if (endPos < 0) { endPos = Math.Max(endPos + (int)reader.Length, 0); } var buffer = new byte[endPos - startPos]; reader.Seek(startPos, SeekOrigin.Begin); reader.Read(buffer, 0, buffer.Length); text = encoding.GetString(buffer, 0, buffer.Length); } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text), callbackId); } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } /// <summary> /// Reads application resource as a text /// </summary> /// <param name="options">Path to a resource</param> public void readResourceAsText(string options) { string[] optStrings = getOptionStrings(options); string pathToResource = optStrings[0]; string encStr = optStrings[1]; int start = int.Parse(optStrings[2]); int endMarker = int.Parse(optStrings[3]); string callbackId = optStrings[4]; try { if (pathToResource.StartsWith("/")) { pathToResource = pathToResource.Remove(0, 1); } var resource = Application.GetResourceStream(new Uri(pathToResource, UriKind.Relative)); if (resource == null) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string text; StreamReader streamReader = new StreamReader(resource.Stream); text = streamReader.ReadToEnd(); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text), callbackId); } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } public void truncate(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; int size = int.Parse(optStrings[1]); string callbackId = optStrings[2]; try { long streamLength = 0; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= size && size <= stream.Length) { stream.SetLength(size); } streamLength = stream.Length; } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, streamLength), callbackId); } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } //write:[filePath,data,position,isBinary,callbackId] public void write(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; string data = optStrings[1]; int position = int.Parse(optStrings[2]); bool isBinary = bool.Parse(optStrings[3]); string callbackId = optStrings[4]; try { if (string.IsNullOrEmpty(data)) { Debug.WriteLine("Expected some data to be send in the write command to {0}", filePath); DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); return; } byte[] dataToWrite = isBinary ? JSON.JsonHelper.Deserialize<byte[]>(data) : System.Text.Encoding.UTF8.GetBytes(data); using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // create the file if not exists if (!isoFile.FileExists(filePath)) { var file = isoFile.CreateFile(filePath); file.Close(); } using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= position && position <= stream.Length) { stream.SetLength(position); } using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Seek(0, SeekOrigin.End); writer.Write(dataToWrite); } } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, dataToWrite.Length), callbackId); } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } /// <summary> /// Look up metadata about this entry. /// </summary> /// <param name="options">filePath to entry</param> public void getMetadata(string options) { string[] optStings = getOptionStrings(options); string filePath = optStings[0]; string callbackId = optStings[1]; if (filePath != null) { try { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoFile.FileExists(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new ModificationMetadata() { modificationTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString() }), callbackId); } else if (isoFile.DirectoryExists(filePath)) { string modTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString(); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new ModificationMetadata() { modificationTime = modTime }), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } catch (IsolatedStorageException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } } /// <summary> /// Returns a File that represents the current state of the file that this FileEntry represents. /// </summary> /// <param name="filePath">filePath to entry</param> /// <returns></returns> public void getFileMetadata(string options) { string[] optStings = getOptionStrings(options); string filePath = optStings[0]; string callbackId = optStings[1]; if (!string.IsNullOrEmpty(filePath)) { try { FileMetadata metaData = new FileMetadata(filePath); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, metaData), callbackId); } catch (IsolatedStorageException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } /// <summary> /// Look up the parent DirectoryEntry containing this Entry. /// If this Entry is the root of IsolatedStorage, its parent is itself. /// </summary> /// <param name="options"></param> public void getParent(string options) { string[] optStings = getOptionStrings(options); string filePath = optStings[0]; string callbackId = optStings[1]; if (filePath != null) { try { if (string.IsNullOrEmpty(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId); return; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { FileEntry entry; if (isoFile.FileExists(filePath) || isoFile.DirectoryExists(filePath)) { string path = this.GetParentDirectory(filePath); entry = FileEntry.GetEntry(path); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry),callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); } } } } public void remove(string options) { string[] args = getOptionStrings(options); string filePath = args[0]; string callbackId = args[1]; if (filePath != null) { try { if (filePath == "/" || filePath == "" || filePath == @"\") { throw new Exception("Cannot delete root file system") ; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoFile.FileExists(filePath)) { isoFile.DeleteFile(filePath); } else { if (isoFile.DirectoryExists(filePath)) { isoFile.DeleteDirectory(filePath); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); return; } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK),callbackId); } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId); } } } } public void removeRecursively(string options) { string[] args = getOptionStrings(options); string filePath = args[0]; string callbackId = args[1]; if (filePath != null) { if (string.IsNullOrEmpty(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId); } else { if (removeDirRecursively(filePath, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } } } } public void readEntries(string options) { string[] args = getOptionStrings(options); string filePath = args[0]; string callbackId = args[1]; if (filePath != null) { try { if (string.IsNullOrEmpty(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId); return; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoFile.DirectoryExists(filePath)) { string path = File.AddSlashToDirectory(filePath); List<FileEntry> entries = new List<FileEntry>(); string[] files = isoFile.GetFileNames(path + "*"); string[] dirs = isoFile.GetDirectoryNames(path + "*"); foreach (string file in files) { entries.Add(FileEntry.GetEntry(path + file)); } foreach (string dir in dirs) { entries.Add(FileEntry.GetEntry(path + dir + "/")); } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entries),callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId); } } } } public void requestFileSystem(string options) { // TODO: try/catch string[] optVals = getOptionStrings(options); //FileOptions fileOptions = new FileOptions(); int fileSystemType = int.Parse(optVals[0]); double size = double.Parse(optVals[1]); string callbackId = optVals[2]; IsolatedStorageFile.GetUserStoreForApplication(); if (size > (10 * 1024 * 1024)) // 10 MB, compier will clean this up! { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR), callbackId); return; } try { if (size != 0) { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { long availableSize = isoFile.AvailableFreeSpace; if (size > availableSize) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR), callbackId); return; } } } if (fileSystemType == PERSISTENT) { // TODO: this should be in it's own folder to prevent overwriting of the app assets, which are also in ISO DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("persistent", FileEntry.GetEntry("/"))), callbackId); } else if (fileSystemType == TEMPORARY) { using (IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoStorage.FileExists(TMP_DIRECTORY_NAME)) { isoStorage.CreateDirectory(TMP_DIRECTORY_NAME); } } string tmpFolder = "/" + TMP_DIRECTORY_NAME + "/"; DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("temporary", FileEntry.GetEntry(tmpFolder))), callbackId); } else if (fileSystemType == RESOURCE) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("resource")), callbackId); } else if (fileSystemType == APPLICATION) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("application")), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } public void resolveLocalFileSystemURI(string options) { string[] optVals = getOptionStrings(options); string uri = optVals[0].Split('?')[0]; string callbackId = optVals[1]; if (uri != null) { // a single '/' is valid, however, '/someDir' is not, but '/tmp//somedir' and '///someDir' are valid if (uri.StartsWith("/") && uri.IndexOf("//") < 0 && uri != "/") { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); return; } try { // fix encoded spaces string path = Uri.UnescapeDataString(uri); FileEntry uriEntry = FileEntry.GetEntry(path); if (uriEntry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, uriEntry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } } public void copyTo(string options) { TransferTo(options, false); } public void moveTo(string options) { TransferTo(options, true); } public void getFile(string options) { GetFileOrDirectory(options, false); } public void getDirectory(string options) { GetFileOrDirectory(options, true); } #region internal functionality /// <summary> /// Retrieves the parent directory name of the specified path, /// </summary> /// <param name="path">Path</param> /// <returns>Parent directory name</returns> private string GetParentDirectory(string path) { if (String.IsNullOrEmpty(path) || path == "/") { return "/"; } if (path.EndsWith(@"/") || path.EndsWith(@"\")) { return this.GetParentDirectory(Path.GetDirectoryName(path)); } string result = Path.GetDirectoryName(path); if (result == null) { result = "/"; } return result; } private bool removeDirRecursively(string fullPath,string callbackId) { try { if (fullPath == "/") { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId); return false; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoFile.DirectoryExists(fullPath)) { string tempPath = File.AddSlashToDirectory(fullPath); string[] files = isoFile.GetFileNames(tempPath + "*"); if (files.Length > 0) { foreach (string file in files) { isoFile.DeleteFile(tempPath + file); } } string[] dirs = isoFile.GetDirectoryNames(tempPath + "*"); if (dirs.Length > 0) { foreach (string dir in dirs) { if (!removeDirRecursively(tempPath + dir, callbackId)) { return false; } } } isoFile.DeleteDirectory(fullPath); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId); return false; } } return true; } private bool CanonicalCompare(string pathA, string pathB) { string a = pathA.Replace("//", "/"); string b = pathB.Replace("//", "/"); return a.Equals(b, StringComparison.OrdinalIgnoreCase); } /* * copyTo:["fullPath","parent", "newName"], * moveTo:["fullPath","parent", "newName"], */ private void TransferTo(string options, bool move) { // TODO: try/catch string[] optStrings = getOptionStrings(options); string fullPath = optStrings[0]; string parent = optStrings[1]; string newFileName = optStrings[2]; string callbackId = optStrings[3]; char[] invalids = Path.GetInvalidPathChars(); if (newFileName.IndexOfAny(invalids) > -1 || newFileName.IndexOf(":") > -1 ) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); return; } try { if ((parent == null) || (string.IsNullOrEmpty(parent)) || (string.IsNullOrEmpty(fullPath))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string parentPath = File.AddSlashToDirectory(parent); string currentPath = fullPath; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { bool isFileExist = isoFile.FileExists(currentPath); bool isDirectoryExist = isoFile.DirectoryExists(currentPath); bool isParentExist = isoFile.DirectoryExists(parentPath); if ( ( !isFileExist && !isDirectoryExist ) || !isParentExist ) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string newName; string newPath; if (isFileExist) { newName = (string.IsNullOrEmpty(newFileName)) ? Path.GetFileName(currentPath) : newFileName; newPath = Path.Combine(parentPath, newName); // sanity check .. // cannot copy file onto itself if (CanonicalCompare(newPath,currentPath)) //(parent + newFileName)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId); return; } else if (isoFile.DirectoryExists(newPath)) { // there is already a folder with the same name, operation is not allowed DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId); return; } else if (isoFile.FileExists(newPath)) { // remove destination file if exists, in other case there will be exception isoFile.DeleteFile(newPath); } if (move) { isoFile.MoveFile(currentPath, newPath); } else { isoFile.CopyFile(currentPath, newPath, true); } } else { newName = (string.IsNullOrEmpty(newFileName)) ? currentPath : newFileName; newPath = Path.Combine(parentPath, newName); if (move) { // remove destination directory if exists, in other case there will be exception // target directory should be empty if (!newPath.Equals(currentPath) && isoFile.DirectoryExists(newPath)) { isoFile.DeleteDirectory(newPath); } isoFile.MoveDirectory(currentPath, newPath); } else { CopyDirectory(currentPath, newPath, isoFile); } } FileEntry entry = FileEntry.GetEntry(newPath); if (entry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } private bool HandleException(Exception ex, string cbId="") { bool handled = false; string callbackId = String.IsNullOrEmpty(cbId) ? this.CurrentCommandCallbackId : cbId; if (ex is SecurityException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, SECURITY_ERR), callbackId); handled = true; } else if (ex is FileNotFoundException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); handled = true; } else if (ex is ArgumentException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); handled = true; } else if (ex is IsolatedStorageException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId); handled = true; } else if (ex is DirectoryNotFoundException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); handled = true; } return handled; } private void CopyDirectory(string sourceDir, string destDir, IsolatedStorageFile isoFile) { string path = File.AddSlashToDirectory(sourceDir); bool bExists = isoFile.DirectoryExists(destDir); if (!bExists) { isoFile.CreateDirectory(destDir); } destDir = File.AddSlashToDirectory(destDir); string[] files = isoFile.GetFileNames(path + "*"); if (files.Length > 0) { foreach (string file in files) { isoFile.CopyFile(path + file, destDir + file,true); } } string[] dirs = isoFile.GetDirectoryNames(path + "*"); if (dirs.Length > 0) { foreach (string dir in dirs) { CopyDirectory(path + dir, destDir + dir, isoFile); } } } private string RemoveExtraSlash(string path) { if (path.StartsWith("//")) { path = path.Remove(0, 1); path = RemoveExtraSlash(path); } return path; } private string ResolvePath(string parentPath, string path) { string absolutePath = null; if (path.Contains("..")) { if (parentPath.Length > 1 && parentPath.StartsWith("/") && parentPath !="/") { parentPath = RemoveExtraSlash(parentPath); } string fullPath = Path.GetFullPath(Path.Combine(parentPath, path)); absolutePath = fullPath.Replace(Path.GetPathRoot(fullPath), @"//"); } else { absolutePath = Path.Combine(parentPath + "/", path); } return absolutePath; } private void GetFileOrDirectory(string options, bool getDirectory) { FileOptions fOptions = new FileOptions(); string[] args = getOptionStrings(options); fOptions.FullPath = args[0]; fOptions.Path = args[1]; string callbackId = args[3]; try { fOptions.CreatingOpt = JSON.JsonHelper.Deserialize<CreatingOptions>(args[2]); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); return; } try { if ((string.IsNullOrEmpty(fOptions.Path)) || (string.IsNullOrEmpty(fOptions.FullPath))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } string path; if (fOptions.Path.Split(':').Length > 2) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); return; } try { path = ResolvePath(fOptions.FullPath, fOptions.Path); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId); return; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { bool isFile = isoFile.FileExists(path); bool isDirectory = isoFile.DirectoryExists(path); bool create = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Create; bool exclusive = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Exclusive; if (create) { if (exclusive && (isoFile.FileExists(path) || isoFile.DirectoryExists(path))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, PATH_EXISTS_ERR), callbackId); return; } // need to make sure the parent exists // it is an error to create a directory whose immediate parent does not yet exist // see issue: https://issues.apache.org/jira/browse/CB-339 string[] pathParts = path.Split('/'); string builtPath = pathParts[0]; for (int n = 1; n < pathParts.Length - 1; n++) { builtPath += "/" + pathParts[n]; if (!isoFile.DirectoryExists(builtPath)) { Debug.WriteLine(String.Format("Error :: Parent folder \"{0}\" does not exist, when attempting to create \"{1}\"",builtPath,path)); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); return; } } if ((getDirectory) && (!isDirectory)) { isoFile.CreateDirectory(path); } else { if ((!getDirectory) && (!isFile)) { IsolatedStorageFileStream fileStream = isoFile.CreateFile(path); fileStream.Close(); } } } else // (not create) { if ((!isFile) && (!isDirectory)) { if (path.IndexOf("//www") == 0) { Uri fileUri = new Uri(path.Remove(0,2), UriKind.Relative); StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri); if (streamInfo != null) { FileEntry _entry = FileEntry.GetEntry(fileUri.OriginalString,true); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, _entry), callbackId); //using (BinaryReader br = new BinaryReader(streamInfo.Stream)) //{ // byte[] data = br.ReadBytes((int)streamInfo.Stream.Length); //} } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } return; } if (((getDirectory) && (!isDirectory)) || ((!getDirectory) && (!isFile))) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, TYPE_MISMATCH_ERR), callbackId); return; } } FileEntry entry = FileEntry.GetEntry(path); if (entry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId); } } } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId); } } } private static string AddSlashToDirectory(string dirPath) { if (dirPath.EndsWith("/")) { return dirPath; } else { return dirPath + "/"; } } /// <summary> /// Returns file content in a form of base64 string /// </summary> /// <param name="stream">File stream</param> /// <returns>Base64 representation of the file</returns> private string GetFileContent(Stream stream) { int streamLength = (int)stream.Length; byte[] fileData = new byte[streamLength + 1]; stream.Read(fileData, 0, streamLength); stream.Close(); return Convert.ToBase64String(fileData); } #endregion } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Threading; using System.Timers; using Timer=System.Timers.Timer; #endregion /// <summary> /// This is base class for Socket and Session based servers. /// </summary> public abstract class SocketServer : Component { #region Nested type: QueuedConnection /// <summary> /// This struct holds queued connection info. /// </summary> private struct QueuedConnection { #region Members private readonly IPBindInfo m_pBindInfo; private readonly Socket m_pSocket; #endregion #region Properties /// <summary> /// Gets socket. /// </summary> public Socket Socket { get { return m_pSocket; } } /// <summary> /// Gets bind info. /// </summary> public IPBindInfo BindInfo { get { return m_pBindInfo; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="socket">Socket.</param> /// <param name="bindInfo">Bind info.</param> public QueuedConnection(Socket socket, IPBindInfo bindInfo) { m_pSocket = socket; m_pBindInfo = bindInfo; } #endregion } #endregion #region Events /// <summary> /// Occurs when server or session has system error(unhandled error). /// </summary> public event ErrorEventHandler SysError = null; #endregion #region Members private readonly Queue<QueuedConnection> m_pQueuedConnections; private readonly List<SocketServerSession> m_pSessions; private readonly Timer m_pTimer; private int m_MaxBadCommands = 8; private int m_MaxConnections = 1000; private IPBindInfo[] m_pBindInfo; private bool m_Running; private int m_SessionIdleTimeOut = 30000; #endregion #region Properties /// <summary> /// Gets or set socket binding info. Use this property to specify on which IP,port server /// listnes and also if is SSL or STARTTLS support. /// </summary> public IPBindInfo[] BindInfo { get { return m_pBindInfo; } set { if (value == null) { throw new NullReferenceException("BindInfo can't be null !"); } //--- See if bindinfo has changed ----------- bool changed = false; if (m_pBindInfo.Length != value.Length) { changed = true; } else { for (int i = 0; i < m_pBindInfo.Length; i++) { if (!m_pBindInfo[i].Equals(value[i])) { changed = true; break; } } } //------------------------------------------- if (changed) { // If server is currently running, stop it before applying bind info. bool running = m_Running; if (running) { StopServer(); } m_pBindInfo = value; // We need to restart server to take effect IP or Port change if (running) { StartServer(); } } } } /// <summary> /// Gets or sets maximum allowed connections. /// </summary> public int MaxConnections { get { return m_MaxConnections; } set { m_MaxConnections = value; } } /// <summary> /// Runs and stops server. /// </summary> public bool Enabled { get { return m_Running; } set { if (value != m_Running & !DesignMode) { if (value) { StartServer(); } else { StopServer(); } } } } /// <summary> /// Gets or sets if to log commands. /// </summary> public bool LogCommands { get; set; } /// <summary> /// Session idle timeout in milliseconds. /// </summary> public int SessionIdleTimeOut { get { return m_SessionIdleTimeOut; } set { m_SessionIdleTimeOut = value; } } /// <summary> /// Gets or sets maximum bad commands allowed to session. /// </summary> public int MaxBadCommands { get { return m_MaxBadCommands; } set { m_MaxBadCommands = value; } } /// <summary> /// Gets active sessions. /// </summary> public SocketServerSession[] Sessions { get { return m_pSessions.ToArray(); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SocketServer() { m_pSessions = new List<SocketServerSession>(); m_pQueuedConnections = new Queue<QueuedConnection>(); m_pTimer = new Timer(15000); m_pBindInfo = new[] { new IPBindInfo(System.Net.Dns.GetHostName(), IPAddress.Any, 10000, SslMode.None, null) }; m_pTimer.AutoReset = true; m_pTimer.Elapsed += m_pTimer_Elapsed; } #endregion #region Methods /// <summary> /// Clean up any resources being used and stops server. /// </summary> public new void Dispose() { base.Dispose(); StopServer(); } /// <summary> /// Starts server. /// </summary> public void StartServer() { if (!m_Running) { m_Running = true; // Start accepting ang queueing connections Thread tr = new Thread(StartProcCons); tr.Start(); // Start proccessing queued connections Thread trSessionCreator = new Thread(StartProcQueuedCons); trSessionCreator.Start(); m_pTimer.Enabled = true; } } /// <summary> /// Stops server. NOTE: Active sessions aren't cancled. /// </summary> public void StopServer() { if (m_Running) { m_Running = false; // Stop accepting new connections foreach (IPBindInfo bindInfo in m_pBindInfo) { if (bindInfo.Tag != null) { ((Socket) bindInfo.Tag).Close(); bindInfo.Tag = null; } } // Wait method StartProcCons to exit Thread.Sleep(100); } } #endregion #region Virtual methods /// <summary> /// Initialize and start new session here. Session isn't added to session list automatically, /// session must add itself to server session list by calling AddSession(). /// </summary> /// <param name="socket">Connected client socket.</param> /// <param name="bindInfo">BindInfo what accepted socket.</param> protected virtual void InitNewSession(Socket socket, IPBindInfo bindInfo) {} #endregion #region Event handlers private void m_pTimer_Elapsed(object sender, ElapsedEventArgs e) { OnSessionTimeoutTimer(); } #endregion #region Utility methods /// <summary> /// Starts proccessiong incoming connections (Accepts and queues connections). /// </summary> private void StartProcCons() { try { CircleCollection<IPBindInfo> binds = new CircleCollection<IPBindInfo>(); foreach (IPBindInfo bindInfo in m_pBindInfo) { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Bind(new IPEndPoint(bindInfo.IP, bindInfo.Port)); s.Listen(500); bindInfo.Tag = s; binds.Add(bindInfo); } // Accept connections and queue them while (m_Running) { // We have reached maximum connection limit if (m_pSessions.Count > m_MaxConnections) { // Wait while some active connectins are closed while (m_pSessions.Count > m_MaxConnections) { Thread.Sleep(100); } } // Get incomong connection IPBindInfo bindInfo = binds.Next(); // There is waiting connection if (m_Running && ((Socket) bindInfo.Tag).Poll(0, SelectMode.SelectRead)) { // Accept incoming connection Socket s = ((Socket) bindInfo.Tag).Accept(); // Add session to queue lock (m_pQueuedConnections) { m_pQueuedConnections.Enqueue(new QueuedConnection(s, bindInfo)); } } Thread.Sleep(2); } } catch (SocketException x) { // Socket listening stopped, happens when StopServer is called. // We need just skip this error. if (x.ErrorCode == 10004) {} else { OnSysError("WE MUST NEVER REACH HERE !!! StartProcCons:", x); } } catch (Exception x) { OnSysError("WE MUST NEVER REACH HERE !!! StartProcCons:", x); } } /// <summary> /// Starts queueed connections proccessing (Creates and starts session foreach queued connection). /// </summary> private void StartProcQueuedCons() { try { while (m_Running) { // There are queued connections, start sessions. if (m_pQueuedConnections.Count > 0) { QueuedConnection connection; lock (m_pQueuedConnections) { connection = m_pQueuedConnections.Dequeue(); } try { InitNewSession(connection.Socket, connection.BindInfo); } catch (Exception x) { OnSysError("StartProcQueuedCons InitNewSession():", x); } } // There are no connections to proccess, delay proccessing. We need to it // because if there are no connections to proccess, while loop takes too much CPU. else { Thread.Sleep(10); } } } catch (Exception x) { OnSysError("WE MUST NEVER REACH HERE !!! StartProcQueuedCons:", x); } } /// <summary> /// This method must get timedout sessions and end them. /// </summary> private void OnSessionTimeoutTimer() { try { // Close/Remove timed out sessions lock (m_pSessions) { SocketServerSession[] sessions = Sessions; // Loop sessions and and call OnSessionTimeout() for timed out sessions. for (int i = 0; i < sessions.Length; i++) { // If session throws exception, handle it here or next sessions timouts are not handled. try { // Session timed out if (DateTime.Now > sessions[i].SessionLastDataTime.AddMilliseconds(SessionIdleTimeOut)) { sessions[i].OnSessionTimeout(); } } catch (Exception x) { OnSysError("OnTimer:", x); } } } } catch (Exception x) { OnSysError("WE MUST NEVER REACH HERE !!! OnTimer:", x); } } #endregion /// <summary> /// Adds specified session to sessions collection. /// </summary> /// <param name="session">Session to add.</param> protected internal void AddSession(SocketServerSession session) { lock (m_pSessions) { m_pSessions.Add(session); } } /// <summary> /// Removes specified session from sessions collection. /// </summary> /// <param name="session">Session to remove.</param> protected internal void RemoveSession(SocketServerSession session) { lock (m_pSessions) { m_pSessions.Remove(session); } } /// <summary> /// /// </summary> /// <param name="text"></param> /// <param name="x"></param> protected internal void OnSysError(string text, Exception x) { if (SysError != null) { SysError(this, new Error_EventArgs(x, new StackTrace())); } } } }
// 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.Linq; using Xunit; using Validation; using System.Diagnostics; namespace System.Collections.Immutable.Test { public abstract class ImmutableListTestBase : SimpleElementImmutablesTestBase { internal abstract IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list); [Fact] public void CopyToEmptyTest() { var array = new int[0]; this.GetListQuery(ImmutableList<int>.Empty).CopyTo(array); this.GetListQuery(ImmutableList<int>.Empty).CopyTo(array, 0); this.GetListQuery(ImmutableList<int>.Empty).CopyTo(0, array, 0, 0); ((ICollection)this.GetListQuery(ImmutableList<int>.Empty)).CopyTo(array, 0); } [Fact] public void CopyToTest() { var listQuery = this.GetListQuery(ImmutableList.Create(1, 2)); var list = (IEnumerable<int>)listQuery; var array = new int[2]; listQuery.CopyTo(array); Assert.Equal(list, array); array = new int[2]; listQuery.CopyTo(array, 0); Assert.Equal(list, array); array = new int[2]; listQuery.CopyTo(0, array, 0, listQuery.Count); Assert.Equal(list, array); array = new int[1]; // shorter than source length listQuery.CopyTo(0, array, 0, array.Length); Assert.Equal(list.Take(array.Length), array); array = new int[3]; listQuery.CopyTo(1, array, 2, 1); Assert.Equal(new[] { 0, 0, 2 }, array); array = new int[2]; ((ICollection)listQuery).CopyTo(array, 0); Assert.Equal(list, array); } [Fact] public void ForEachTest() { this.GetListQuery(ImmutableList<int>.Empty).ForEach(n => { throw new ShouldNotBeInvokedException(); }); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 3)); var hitTest = new bool[list.Max() + 1]; this.GetListQuery(list).ForEach(i => { Assert.False(hitTest[i]); hitTest[i] = true; }); for (int i = 0; i < hitTest.Length; i++) { Assert.Equal(list.Contains(i), hitTest[i]); Assert.Equal(((IList)list).Contains(i), hitTest[i]); } } [Fact] public void ExistsTest() { Assert.False(this.GetListQuery(ImmutableList<int>.Empty).Exists(n => true)); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 5)); Assert.True(this.GetListQuery(list).Exists(n => n == 3)); Assert.False(this.GetListQuery(list).Exists(n => n == 8)); } [Fact] public void FindAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).FindAll(n => true).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); var actual = this.GetListQuery(list).FindAll(n => n % 2 == 1); var expected = list.ToList().FindAll(n => n % 2 == 1); Assert.Equal<int>(expected, actual.ToList()); } [Fact] public void FindTest() { Assert.Equal(0, this.GetListQuery(ImmutableList<int>.Empty).Find(n => true)); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); Assert.Equal(3, this.GetListQuery(list).Find(n => (n % 2) == 1)); } [Fact] public void FindLastTest() { Assert.Equal(0, this.GetListQuery(ImmutableList<int>.Empty).FindLast(n => { throw new ShouldNotBeInvokedException(); })); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); Assert.Equal(5, this.GetListQuery(list).FindLast(n => (n % 2) == 1)); } [Fact] public void FindIndexTest() { Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(0, n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(0, 0, n => true)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, this.GetListQuery(list).FindIndex(n => n == 6)); for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= list.Count - idx; count++) { foreach (int c in list) { int predicateInvocationCount = 0; Predicate<int> match = n => { predicateInvocationCount++; return n == c; }; int expected = bclList.FindIndex(idx, count, match); int expectedInvocationCount = predicateInvocationCount; predicateInvocationCount = 0; int actual = this.GetListQuery(list).FindIndex(idx, count, match); int actualInvocationCount = predicateInvocationCount; Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (count == list.Count) { // Also test the FindIndex overload that takes no count parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindIndex(idx, match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (idx == 0) { // Also test the FindIndex overload that takes no index parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindIndex(match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); } } } } } } [Fact] public void FindLastIndexTest() { Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(0, n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(0, 0, n => true)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, this.GetListQuery(list).FindLastIndex(n => n == 6)); for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= idx + 1; count++) { foreach (int c in list) { int predicateInvocationCount = 0; Predicate<int> match = n => { predicateInvocationCount++; return n == c; }; int expected = bclList.FindLastIndex(idx, count, match); int expectedInvocationCount = predicateInvocationCount; predicateInvocationCount = 0; int actual = this.GetListQuery(list).FindLastIndex(idx, count, match); int actualInvocationCount = predicateInvocationCount; Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (count == list.Count) { // Also test the FindIndex overload that takes no count parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindLastIndex(idx, match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (idx == list.Count - 1) { // Also test the FindIndex overload that takes no index parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindLastIndex(match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); } } } } } } [Fact] public void ConvertAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).ConvertAll<float>(n => n).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); Func<int, double> converter = n => 2.0 * n; var expected = list.ToList().Select(converter).ToList(); var actual = this.GetListQuery(list).ConvertAll(converter); Assert.Equal<double>(expected.ToList(), actual.ToList()); } [Fact] public void GetRangeTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).GetRange(0, 0).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); var bclList = list.ToList(); for (int index = 0; index < list.Count; index++) { for (int count = 0; count < list.Count - index; count++) { var expected = bclList.GetRange(index, count); var actual = this.GetListQuery(list).GetRange(index, count); Assert.Equal<int>(expected.ToList(), actual.ToList()); } } } [Fact] public void TrueForAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).TrueForAll(n => false)); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); this.TrueForAllTestHelper(list, n => n % 2 == 0); this.TrueForAllTestHelper(list, n => n % 2 == 1); this.TrueForAllTestHelper(list, n => true); } [Fact] public void RemoveAllTest() { var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); this.RemoveAllTestHelper(list, n => false); this.RemoveAllTestHelper(list, n => true); this.RemoveAllTestHelper(list, n => n < 7); this.RemoveAllTestHelper(list, n => n > 7); this.RemoveAllTestHelper(list, n => n == 7); } [Fact] public void ReverseTest() { var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); for (int i = 0; i < list.Count; i++) { for (int j = 0; j < list.Count - i; j++) { this.ReverseTestHelper(list, i, j); } } } [Fact] public void SortTest() { var scenarios = new[] { ImmutableList<int>.Empty, ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 50)), ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 50).Reverse()), }; foreach (var scenario in scenarios) { var expected = scenario.ToList(); expected.Sort(); var actual = this.SortTestHelper(scenario); Assert.Equal<int>(expected, actual); expected = scenario.ToList(); Comparison<int> comparison = (x, y) => x > y ? 1 : (x < y ? -1 : 0); expected.Sort(comparison); actual = this.SortTestHelper(scenario, comparison); Assert.Equal<int>(expected, actual); expected = scenario.ToList(); IComparer<int> comparer = Comparer<int>.Default; expected.Sort(comparer); actual = this.SortTestHelper(scenario, comparer); Assert.Equal<int>(expected, actual); for (int i = 0; i < scenario.Count; i++) { for (int j = 0; j < scenario.Count - i; j++) { expected = scenario.ToList(); comparer = Comparer<int>.Default; expected.Sort(i, j, comparer); actual = this.SortTestHelper(scenario, i, j, comparer); Assert.Equal<int>(expected, actual); } } } } [Fact] public void BinarySearch() { var basis = new List<int>(Enumerable.Range(1, 50).Select(n => n * 2)); var query = this.GetListQuery(basis.ToImmutableList()); for (int value = basis.First() - 1; value <= basis.Last() + 1; value++) { int expected = basis.BinarySearch(value); int actual = query.BinarySearch(value); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); for (int index = 0; index < basis.Count - 1; index++) { for (int count = 0; count <= basis.Count - index; count++) { expected = basis.BinarySearch(index, count, value, null); actual = query.BinarySearch(index, count, value, null); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); } } } } [Fact] public void BinarySearchPartialSortedList() { var reverseSorted = ImmutableArray.CreateRange(Enumerable.Range(1, 150).Select(n => n * 2).Reverse()); this.BinarySearchPartialSortedListHelper(reverseSorted, 0, 50); this.BinarySearchPartialSortedListHelper(reverseSorted, 50, 50); this.BinarySearchPartialSortedListHelper(reverseSorted, 100, 50); } private void BinarySearchPartialSortedListHelper(ImmutableArray<int> inputData, int sortedIndex, int sortedLength) { Requires.Range(sortedIndex >= 0, "sortedIndex"); Requires.Range(sortedLength > 0, "sortedLength"); inputData = inputData.Sort(sortedIndex, sortedLength, Comparer<int>.Default); int min = inputData[sortedIndex]; int max = inputData[sortedIndex + sortedLength - 1]; var basis = new List<int>(inputData); var query = this.GetListQuery(inputData.ToImmutableList()); for (int value = min - 1; value <= max + 1; value++) { for (int index = sortedIndex; index < sortedIndex + sortedLength; index++) // make sure the index we pass in is always within the sorted range in the list. { for (int count = 0; count <= sortedLength - index; count++) { int expected = basis.BinarySearch(index, count, value, null); int actual = query.BinarySearch(index, count, value, null); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); } } } } [Fact] public void SyncRoot() { var collection = (ICollection)this.GetEnumerableOf<int>(); Assert.NotNull(collection.SyncRoot); Assert.Same(collection.SyncRoot, collection.SyncRoot); } [Fact] public void GetEnumeratorTest() { var enumerable = this.GetEnumerableOf(1); Assert.Equal(new[] { 1 }, enumerable.ToList()); // exercises the enumerator IEnumerable enumerableNonGeneric = enumerable; Assert.Equal(new[] { 1 }, enumerableNonGeneric.Cast<int>().ToList()); // exercises the enumerator } protected abstract void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test); protected abstract void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer); private void TrueForAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test) { var bclList = list.ToList(); var expected = bclList.TrueForAll(test); var actual = this.GetListQuery(list).TrueForAll(test); Assert.Equal(expected, actual); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AddScalarDouble() { var test = new SimpleBinaryOpTest__AddScalarDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddScalarDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddScalarDouble testClass) { var result = Sse2.AddScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddScalarDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.AddScalar( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddScalarDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__AddScalarDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.AddScalar( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.AddScalar( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.AddScalar( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AddScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AddScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AddScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.AddScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.AddScalar( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.AddScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.AddScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.AddScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddScalarDouble(); var result = Sse2.AddScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AddScalarDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.AddScalar( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.AddScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.AddScalar( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.AddScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.AddScalar( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(left[0] + right[0]) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(left[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.AddScalar)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // FileManager.cs // // Author: Kees van Spelde <sicos2002@hotmail.com> // // Copyright (c) 2014-2021 Magic-Sessions. (www.magic-sessions.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. 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.Globalization; using System.IO; using System.Linq; namespace VCardReader.Helpers { /// <summary> /// This class contains file management functions that are not available in the .NET framework /// </summary> internal static class FileManager { #region Consts /// <summary> /// The max path length in Windows /// </summary> private const int MaxPath = 248; #endregion #region CheckForBackSlash /// <summary> /// Check if there is a backslash at the end of the string and if not add it /// </summary> /// <param name="line"></param> /// <returns></returns> public static string CheckForBackSlash(string line) { if (line.EndsWith("\\")) return line; return line + "\\"; } #endregion #region ValidateLongFileName /// <summary> /// Validates the length of <paramref name="fileName"/>, when this is longer then <see cref="MaxPath"/> chars it will be truncated. /// </summary> /// <param name="fileName">The filename with path</param> /// <param name="extraTruncateSize">Optional extra truncate size, when not used the filename is truncated until it fits</param> /// <returns></returns> /// <exception cref="ArgumentException">Raised when no path or file name is given in the <paramref name="fileName"/></exception> /// <exception cref="PathTooLongException">Raised when it is not possible to truncate the <paramref name="fileName"/></exception> public static string ValidateLongFileName(string fileName, int extraTruncateSize = -1) { var fileNameWithoutExtension = GetFileNameWithoutExtension(fileName); if (string.IsNullOrWhiteSpace(fileNameWithoutExtension)) throw new ArgumentException(@"No file name is given, e.g. c:\temp\temp.txt", "fileName"); var extension = GetExtension(fileName); if (string.IsNullOrWhiteSpace(extension)) extension = string.Empty; var path = GetDirectoryName(fileName); if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException(@"No path is given, e.g. c:\temp\temp.txt", "fileName"); path = CheckForBackSlash(path); if (fileName.Length <= MaxPath) return fileName; var maxFileNameLength = MaxPath - path.Length - extension.Length; if (extraTruncateSize != -1) maxFileNameLength -= extraTruncateSize; if (maxFileNameLength < 1) throw new PathTooLongException("Unable the truncate the fileName '" + fileName + "', current size '" + fileName.Length + "'"); return path + fileNameWithoutExtension.Substring(0, maxFileNameLength) + extension; } #endregion #region GetExtension /// <summary> /// Returns the extension of the specified <paramref name="path"/> string /// </summary> /// <param name="path">The path of the file</param> /// <returns></returns> /// <exception cref="ArgumentException">Raised when no path is given</exception> public static string GetExtension(string path) { if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("path"); var splittedPath = path.Split(Path.DirectorySeparatorChar); var fileName = splittedPath[splittedPath.Length - 1]; var index = fileName.LastIndexOf(".", StringComparison.Ordinal); return index == -1 ? string.Empty : fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal), fileName.Length - index); } #endregion #region GetFileNameWithoutExtension /// <summary> /// Returns the file name of the specified <paramref name="path"/> string without the extension /// </summary> /// <param name="path">The path of the file</param> /// <returns></returns> /// <exception cref="ArgumentException"></exception> public static string GetFileNameWithoutExtension(string path) { if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException(@"No path given", "path"); var splittedPath = path.Split(Path.DirectorySeparatorChar); var fileName = splittedPath[splittedPath.Length - 1]; return !fileName.Contains(".") ? fileName : fileName.Substring(0, fileName.LastIndexOf(".", StringComparison.Ordinal)); } #endregion #region GetDirectoryName /// <summary> /// Returns the directory information for the specified <paramref name="path"/> string /// </summary> /// <param name="path">The path of a file or directory</param> /// <returns></returns> public static string GetDirectoryName(string path) { //GetDirectoryName('C:\MyDir\MySubDir\myfile.ext') returns 'C:\MyDir\MySubDir' //GetDirectoryName('C:\MyDir\MySubDir') returns 'C:\MyDir' //GetDirectoryName('C:\MyDir\') returns 'C:\MyDir' //GetDirectoryName('C:\MyDir') returns 'C:\' //GetDirectoryName('C:\') returns '' var splittedPath = path.Split(Path.DirectorySeparatorChar); if (splittedPath.Length <= 1) return string.Empty; var result = splittedPath[0]; for (var i = 1; i < splittedPath.Length - 1; i++) result += Path.DirectorySeparatorChar + splittedPath[i]; return result; } #endregion #region FileExistsMakeNew /// <summary> /// Checks if a file already exists and if so adds a number until the file is unique /// </summary> /// <param name="fileName">The file to check</param> /// <param name="validateLongFileName">When true validation will be performed on the max path lengt</param> /// <param name="extraTruncateSize"></param> /// <returns></returns> /// <exception cref="ArgumentException">Raised when no path or file name is given in the <paramref name="fileName"/></exception> /// <exception cref="PathTooLongException">Raised when it is not possible to truncate the <paramref name="fileName"/></exception> public static string FileExistsMakeNew(string fileName, bool validateLongFileName = true, int extraTruncateSize = -1) { var fileNameWithoutExtension = GetFileNameWithoutExtension(fileName); var extension = GetExtension(fileName); var path = CheckForBackSlash(GetDirectoryName(fileName)); var tempFileName = validateLongFileName ? ValidateLongFileName(fileName, extraTruncateSize) : fileName; var i = 2; while (File.Exists(tempFileName)) { tempFileName = path + fileNameWithoutExtension + "_" + i + extension; tempFileName = validateLongFileName ? ValidateLongFileName(tempFileName, extraTruncateSize) : tempFileName; i += 1; } return tempFileName; } #endregion #region RemoveInvalidFileNameChars /// <summary> /// Removes illegal filename characters /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static string RemoveInvalidFileNameChars(string fileName) { return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(CultureInfo.InvariantCulture), string.Empty)); } #endregion #region GetFileSizeString /// <summary> /// Gives the size of a file in Windows format (GB, MB, KB, Bytes) /// </summary> /// <param name="bytes">Filesize in bytes</param> /// <returns></returns> public static string GetFileSizeString(double bytes) { var size = "0 Bytes"; if (bytes >= 1073741824.0) size = String.Format(CultureInfo.InvariantCulture, "{0:##.##}", bytes / 1073741824.0) + " GB"; else if (bytes >= 1048576.0) size = String.Format(CultureInfo.InvariantCulture, "{0:##.##}", bytes / 1048576.0) + " MB"; else if (bytes >= 1024.0) size = String.Format(CultureInfo.InvariantCulture, "{0:##.##}", bytes / 1024.0) + " KB"; else if (bytes > 0 && bytes < 1024.0) size = bytes + " Bytes"; return size; } #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.Collections; using System.Text; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Globalization; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using System.Runtime.InteropServices; namespace Microsoft.Build.Utilities { /// <summary> /// Enumeration to express the type of executable being wrapped by Tracker.exe /// </summary> public enum ExecutableType { /// <summary> /// 32-bit native executable /// </summary> Native32Bit = 0, /// <summary> /// 64-bit native executable /// </summary> Native64Bit = 1, /// <summary> /// A managed executable without a specified bitness /// </summary> ManagedIL = 2, /// <summary> /// A managed executable specifically marked as 32-bit /// </summary> Managed32Bit = 3, /// <summary> /// A managed executable specifically marked as 64-bit /// </summary> Managed64Bit = 4, /// <summary> /// Use the same bitness as the currently running executable. /// </summary> SameAsCurrentProcess = 5 } /// <summary> /// This class contains utility functions to encapsulate launching and logging for the Tracker /// </summary> public static class FileTracker { #region Static Member Data // The default path to temp, used to create explicitly short and long paths private static string s_tempPath = Path.GetTempPath(); // The short path to temp private static string s_tempShortPath = FileUtilities.EnsureTrailingSlash(NativeMethodsShared.GetShortFilePath(s_tempPath).ToUpperInvariant()); // The long path to temp private static string s_tempLongPath = FileUtilities.EnsureTrailingSlash(NativeMethodsShared.GetLongFilePath(s_tempPath).ToUpperInvariant()); // The path to ApplicationData (is equal to %USERPROFILE%\Application Data folder in Windows XP and %USERPROFILE%\AppData\Roaming in Vista and later) private static string s_applicationDataPath = FileUtilities.EnsureTrailingSlash(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToUpperInvariant()); // The path to LocalApplicationData (is equal to %USERPROFILE%\Local Settings\Application Data folder in Windows XP and %USERPROFILE%\AppData\Local in Vista and later). private static string s_localApplicationDataPath = FileUtilities.EnsureTrailingSlash(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).ToUpperInvariant()); // The path to the LocalLow folder. In Vista and later, user application data is organized across %USERPROFILE%\AppData\LocalLow, %USERPROFILE%\AppData\Local (%LOCALAPPDATA%) // and %USERPROFILE%\AppData\Roaming (%APPDATA%). The LocalLow folder is not present in XP. private static string s_localLowApplicationDataPath = FileUtilities.EnsureTrailingSlash(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "AppData\\LocalLow").ToUpperInvariant()); // The path to the common Application Data, which is also used by some programs (e.g. antivirus) that we wish to ignore. // Is equal to C:\Documents and Settings\All Users\Application Data on XP, and C:\ProgramData on Vista+. // But for backward compatibility, the paths "C:\Documents and Settings\All Users\Application Data" and "C:\Users\All Users\Application Data" are still accessible via Junction point on Vista+. // Thus this list is created to store all possible common application data paths to cover more cases as possible. private static List<string> s_commonApplicationDataPaths; // The name of the standalone tracker tool. private static string s_TrackerFilename = "Tracker.exe"; // The name of the assembly that is injected into the executing process. // Detours handles picking between FileTracker{32,64}.dll so only mention one. private static string s_FileTrackerFilename = "FileTracker32.dll"; #endregion #region Static constructor static FileTracker() { s_commonApplicationDataPaths = new List<string>(); string defaultCommonApplicationDataPath = FileUtilities.EnsureTrailingSlash(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData).ToUpperInvariant()); s_commonApplicationDataPaths.Add(defaultCommonApplicationDataPath); string defaultRootDirectory = Path.GetPathRoot(defaultCommonApplicationDataPath); string alternativeCommonApplicationDataPath1 = FileUtilities.EnsureTrailingSlash(Path.Combine(defaultRootDirectory, @"Documents and Settings\All Users\Application Data").ToUpperInvariant()); if (!alternativeCommonApplicationDataPath1.Equals(defaultCommonApplicationDataPath, StringComparison.Ordinal)) { s_commonApplicationDataPaths.Add(alternativeCommonApplicationDataPath1); } string alternativeCommonApplicationDataPath2 = FileUtilities.EnsureTrailingSlash(Path.Combine(defaultRootDirectory, @"Users\All Users\Application Data").ToUpperInvariant()); if (!alternativeCommonApplicationDataPath2.Equals(defaultCommonApplicationDataPath, StringComparison.Ordinal)) { s_commonApplicationDataPaths.Add(alternativeCommonApplicationDataPath2); } } #endregion #region Native method wrappers /// <summary> /// Stops tracking file accesses. /// </summary> public static void EndTrackingContext() { InprocTrackingNativeMethods.EndTrackingContext(); } /// <summary> /// Resume tracking file accesses in the current tracking context. /// </summary> public static void ResumeTracking() { InprocTrackingNativeMethods.ResumeTracking(); } /// <summary> /// Set the global thread count, and assign that count to the current thread. /// </summary> public static void SetThreadCount(int threadCount) { InprocTrackingNativeMethods.SetThreadCount(threadCount); } /// <summary> /// Starts tracking file accesses. /// </summary> /// <param name="intermediateDirectory">The directory into which to write the tracking log files</param> /// <param name="taskName">The name of the task calling this function, used to determine the /// names of the tracking log files</param> public static void StartTrackingContext(string intermediateDirectory, string taskName) { InprocTrackingNativeMethods.StartTrackingContext(intermediateDirectory, taskName); } /// <summary> /// Starts tracking file accesses, using the rooting marker in the response file provided. To /// automatically generate a response file given a rooting marker, call /// FileTracker.CreateRootingMarkerResponseFile. /// </summary> /// <param name="intermediateDirectory">The directory into which to write the tracking log files</param> /// <param name="taskName">The name of the task calling this function, used to determine the /// names of the tracking log files</param> public static void StartTrackingContextWithRoot(string intermediateDirectory, string taskName, string rootMarkerResponseFile) { InprocTrackingNativeMethods.StartTrackingContextWithRoot(intermediateDirectory, taskName, rootMarkerResponseFile); } /// <summary> /// Stop tracking file accesses and get rid of the current tracking contexts. /// </summary> public static void StopTrackingAndCleanup() { InprocTrackingNativeMethods.StopTrackingAndCleanup(); } /// <summary> /// Temporarily suspend tracking of file accesses in the current tracking context. /// </summary> public static void SuspendTracking() { InprocTrackingNativeMethods.SuspendTracking(); } /// <summary> /// Write tracking logs for all contexts and threads. /// </summary> /// <param name="intermediateDirectory">The directory into which to write the tracking log files</param> /// <param name="taskName">The name of the task calling this function, used to determine the /// names of the tracking log files</param> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLogs", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")] public static void WriteAllTLogs(string intermediateDirectory, string taskName) { InprocTrackingNativeMethods.WriteAllTLogs(intermediateDirectory, taskName); } /// <summary> /// Write tracking logs corresponding to the current tracking context. /// </summary> /// <param name="intermediateDirectory">The directory into which to write the tracking log files</param> /// <param name="taskName">The name of the task calling this function, used to determine the /// names of the tracking log files</param> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLogs", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")] public static void WriteContextTLogs(string intermediateDirectory, string taskName) { InprocTrackingNativeMethods.WriteContextTLogs(intermediateDirectory, taskName); } #endregion // Native method wrappers #region Methods /// <summary> /// Test to see if the specified file is excluded from tracked dependencies /// </summary> /// <param name="fileName"> /// Full path of the file to test /// </param> public static bool FileIsExcludedFromDependencies(string fileName) { bool exclude = true; // UNDONE: This check means that we cannot incremental build projects // that exist under the following directories on XP: // %USERPROFILE%\Application Data // %USERPROFILE%\Local Settings\Application Data // // and the following directories on Vista: // %USERPROFILE%\AppData\Local // %USERPROFILE%\AppData\LocalLow // %USERPROFILE%\AppData\Roaming // We don't want to be including these as dependencies or outputs: // 1. Files under %USERPROFILE%\Application Data in XP and %USERPROFILE%\AppData\Roaming in Vista and later. // 2. Files under %USERPROFILE%\Local Settings\Application Data in XP and %USERPROFILE%\AppData\Local in Vista and later. // 3. Files under %USERPROFILE%\AppData\LocalLow in Vista and later. // 4. Files that are in the TEMP directory (Since on XP, temp files are not // located under AppData, they would not be compacted out correctly otherwise). // 5. Files under the common ("All Users") Application Data location -- C:\Documents and Settings\All Users\Application Data // on XP and either C:\Users\All Users\Application Data or C:\ProgramData on Vista+ exclude = FileTracker.FileIsUnderPath(fileName, s_applicationDataPath) || FileTracker.FileIsUnderPath(fileName, s_localApplicationDataPath) || FileTracker.FileIsUnderPath(fileName, s_localLowApplicationDataPath) || FileTracker.FileIsUnderPath(fileName, s_tempShortPath) || FileTracker.FileIsUnderPath(fileName, s_tempLongPath) || s_commonApplicationDataPaths.Any(p => FileTracker.FileIsUnderPath(fileName, p)); return exclude; } /// <summary> /// Test to see if the specified file is under the specified path /// </summary> /// <param name="fileName"> /// Full path of the file to test /// </param> /// <param name="filePath"> /// Is the file under this full path? /// </param> public static bool FileIsUnderPath(string fileName, string path) { // UNDONE: Get the long file path for the entry // This is an incredibly expensive operation. The tracking log // as written by CL etc. does not contain short paths // fileDirectory = NativeMethods.GetFullLongFilePath(fileDirectory); // Ensure that the path has a trailing slash that we are checking under // By default the paths that we check for most often will have, so this will // return fast and not allocate memory in the process path = FileUtilities.EnsureTrailingSlash(path); // Is the fileName under the filePath? return String.Compare(fileName, 0, path, 0, path.Length, StringComparison.OrdinalIgnoreCase) == 0; } /// <summary> /// Construct a rooting marker string from the ITaskItem array of primary sources. /// </summary> /// <param name="sources"> /// ITaskItem array of primary sources. /// </param> public static string FormatRootingMarker(ITaskItem source) { return FormatRootingMarker(new ITaskItem[] { source }, null); } /// <summary> /// Construct a rooting marker string from the ITaskItem array of primary sources. /// </summary> /// <param name="sources"> /// ITaskItem array of primary sources. /// </param> public static string FormatRootingMarker(ITaskItem source, ITaskItem output) { return FormatRootingMarker(new ITaskItem[] { source }, new ITaskItem[] { output }); } /// <summary> /// Construct a rooting marker string from the ITaskItem array of primary sources. /// </summary> /// <param name="sources"> /// ITaskItem array of primary sources. /// </param> public static string FormatRootingMarker(ITaskItem[] sources) { return FormatRootingMarker(sources, null); } /// <summary> /// Construct a rooting marker string from the ITaskItem array of primary sources. /// </summary> /// <param name="sources"> /// ITaskItem array of primary sources. /// </param> public static string FormatRootingMarker(ITaskItem[] sources, ITaskItem[] outputs) { ErrorUtilities.VerifyThrowArgumentNull(sources, "sources"); ArrayList rootSources = new ArrayList(); StringBuilder rootSourcesList = new StringBuilder(); int builderLength = 0; foreach (ITaskItem source in sources) { rootSources.Add(FileUtilities.NormalizePath(source.ItemSpec).ToUpperInvariant()); } if (outputs != null) { foreach (ITaskItem output in outputs) { rootSources.Add(FileUtilities.NormalizePath(output.ItemSpec).ToUpperInvariant()); } } rootSources.Sort(StringComparer.OrdinalIgnoreCase); foreach (string source in rootSources) { rootSourcesList.Append(source); rootSourcesList.Append('|'); } builderLength = rootSourcesList.Length - 1; if (builderLength < 0) { builderLength = 0; } return rootSourcesList.ToString(0, builderLength); } /// <summary> /// Given a set of source files in the form of ITaskItem, creates a temporary response /// file containing the rooting marker that corresponds to those sources. /// </summary> /// <param name="rootMarker">The rooting marker to put in the response file.</param> /// <returns>The response file path.</returns> public static string CreateRootingMarkerResponseFile(ITaskItem[] sources) { return CreateRootingMarkerResponseFile(FormatRootingMarker(sources)); } /// <summary> /// Given a rooting marker, creates a temporary response file with that rooting marker /// in it. /// </summary> /// <param name="rootMarker">The rooting marker to put in the response file.</param> /// <returns>The response file path.</returns> public static string CreateRootingMarkerResponseFile(string rootMarker) { string trackerResponseFile = FileUtilities.GetTemporaryFile(".rsp"); File.WriteAllText(trackerResponseFile, "/r \"" + rootMarker + "\"", Encoding.Unicode); return trackerResponseFile; } /// <summary> /// Prepends the path to the appropriate FileTracker assembly to the PATH /// environment variable. Used for inproc tracking, or when the .NET Framework may /// not be on the PATH. /// </summary> /// <returns>The old value of PATH</returns> public static string EnsureFileTrackerOnPath() { return EnsureFileTrackerOnPath(null); } /// <summary> /// Prepends the path to the appropriate FileTracker assembly to the PATH /// environment variable. Used for inproc tracking, or when the .NET Framework may /// not be on the PATH. /// </summary> /// <param name="rootPath">The root path for FileTracker.dll. Overrides the toolType if specified.</param> /// <returns>The old value of PATH</returns> public static string EnsureFileTrackerOnPath(string rootPath) { string oldPath = Environment.GetEnvironmentVariable("PATH"); string fileTrackerPath = GetFileTrackerPath(ExecutableType.SameAsCurrentProcess, rootPath); if (!String.IsNullOrEmpty(fileTrackerPath)) { Environment.SetEnvironmentVariable ( "Path", Path.GetDirectoryName(fileTrackerPath) + ";" + oldPath ); } return oldPath; } /// <summary> /// Searches %PATH% for the location of Tracker.exe, and returns the first /// path that matches. /// <returns>Matching full path to Tracker.exe or null if a matching path is not found.</returns> /// </summary> public static string FindTrackerOnPath() { string[] paths = Environment.GetEnvironmentVariable("PATH").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string path in paths) { string trackerPath; try { if (!Path.IsPathRooted(path)) { trackerPath = Path.GetFullPath(path); } else { trackerPath = path; } trackerPath = Path.Combine(trackerPath, s_TrackerFilename); if (File.Exists(trackerPath)) { return trackerPath; } } catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e)) { // ignore this path and move on -- it's just bad for some reason. } } // Still haven't found it. return null; } /// <summary> /// Determines whether we must track out-of-proc, or whether inproc tracking will work. /// </summary> /// <param name="toolType">The executable type for the tool being tracked</param> /// <returns>True if we need to track out-of-proc, false if inproc tracking is OK</returns> public static bool ForceOutOfProcTracking(ExecutableType toolType) { return ForceOutOfProcTracking(toolType, null, null); } /// <summary> /// Determines whether we must track out-of-proc, or whether inproc tracking will work. /// </summary> /// <param name="toolType">The executable type for the tool being tracked</param> /// <param name="cancelEventName">The name of the cancel event tracker should listen for, or null if there isn't one</param> /// <returns>True if we need to track out-of-proc, false if inproc tracking is OK</returns> public static bool ForceOutOfProcTracking(ExecutableType toolType, string dllName, string cancelEventName) { bool trackOutOfProc = false; if (cancelEventName != null) { // If we have a cancel event, we must track out-of-proc. trackOutOfProc = true; } else if (dllName != null) { // If we have a DLL name, we need to track out of proc -- inproc tracking just uses // the default FileTracker trackOutOfProc = true; } // toolType is not relevant now that Detours can handle child processes of a different // bitness than the parent. return trackOutOfProc; } /// <summary> /// Given the ExecutableType of the tool being wrapped and information that we /// know about our current bitness, figures out and returns the path to the correct /// Tracker.exe. /// </summary> /// <param name="toolExecutableTypeToUse">The executable type of the tool being wrapped</param> public static string GetTrackerPath(ExecutableType toolType) { return GetTrackerPath(toolType, null); } /// <summary> /// Given the ExecutableType of the tool being wrapped and information that we /// know about our current bitness, figures out and returns the path to the correct /// Tracker.exe. /// </summary> /// <param name="toolExecutableTypeToUse">The executable type of the tool being wrapped</param> /// <param name="rootPath">The root path for Tracker.exe. Overrides the toolType if specified.</param> public static string GetTrackerPath(ExecutableType toolType, string rootPath) { return GetPath(s_TrackerFilename, toolType, rootPath); } /// <summary> /// Given the ExecutableType of the tool being wrapped and information that we /// know about our current bitness, figures out and returns the path to the correct /// FileTracker.dll. /// </summary> /// <param name="toolExecutableTypeToUse">The executable type of the tool being wrapped</param> public static string GetFileTrackerPath(ExecutableType toolType) { return GetFileTrackerPath(toolType, null); } /// <summary> /// Given the ExecutableType of the tool being wrapped and information that we /// know about our current bitness, figures out and returns the path to the correct /// FileTracker.dll. /// </summary> /// <param name="toolExecutableTypeToUse">The executable type of the tool being wrapped</param> /// <param name="rootPath">The root path for FileTracker.dll. Overrides the toolType if specified.</param> public static string GetFileTrackerPath(ExecutableType toolType, string rootPath) { return GetPath(s_FileTrackerFilename, toolType, rootPath); } /// <summary> /// Given a filename (only really meant to support either Tracker.exe or FileTracker.dll), returns /// the appropriate path for the appropriate file type. /// </summary> /// <param name="filename"></param> /// <param name="toolType"></param> /// <param name="rootPath">The root path for the file. Overrides the toolType if specified.</param> private static string GetPath(string filename, ExecutableType toolType, string rootPath) { string trackerPath = null; if (!String.IsNullOrEmpty(rootPath)) { trackerPath = Path.Combine(rootPath, filename); if (!File.Exists(trackerPath)) { // if an override path was specified, that's it -- we don't want to fall back if the file // is not found there. trackerPath = null; } } else { // Since Detours can handle cross-bitness process launches, the toolType // can be ignored; just return the path corresponding to the current architecture. trackerPath = GetPath(filename, DotNetFrameworkArchitecture.Current); } return trackerPath; } /// <summary> /// Given a filename (currently only Tracker.exe and FileTracker.dll are supported), return /// the path to that file. /// </summary> /// <param name="filename"></param> /// <param name="bitness"></param> /// <returns></returns> private static string GetPath(string filename, DotNetFrameworkArchitecture bitness) { // Make sure that if someone starts passing the wrong thing to this method we don't silently // eat it and do something possibly unexpected. ErrorUtilities.VerifyThrow( s_TrackerFilename.Equals(filename, StringComparison.OrdinalIgnoreCase) || s_FileTrackerFilename.Equals(filename, StringComparison.OrdinalIgnoreCase), "This method should only be passed s_TrackerFilename or s_FileTrackerFilename, but was passed {0} instead!", filename ); // Look for FileTracker.dll/Tracker.exe in the MSBuild tools directory. They may exist elsewhere on disk, // but other copies aren't guaranteed to be compatible with the latest. return ToolLocationHelper.GetPathToBuildToolsFile(filename, ToolLocationHelper.CurrentToolsVersion, bitness); } /// <summary> /// This method constructs the correct Tracker.exe response file arguments from its parameters /// </summary> /// <param name="dllName">The name of the dll that will do the tracking</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <returns>The arguments as a string</returns> public static string TrackerResponseFileArguments(string dllName, string intermediateDirectory, string rootFiles) { return TrackerResponseFileArguments(dllName, intermediateDirectory, rootFiles, null); } /// <summary> /// This method constructs the correct Tracker.exe response file arguments from its parameters /// </summary> /// <param name="dllName">The name of the dll that will do the tracking</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <param name="cancelEventName">If a cancel event has been created that Tracker should be listening for, its name is passed here</param> /// <returns>The arguments as a string</returns> public static string TrackerResponseFileArguments(string dllName, string intermediateDirectory, string rootFiles, string cancelEventName) { CommandLineBuilder builder = new CommandLineBuilder(); builder.AppendSwitchIfNotNull("/d ", dllName); if (!String.IsNullOrEmpty(intermediateDirectory)) { intermediateDirectory = FileUtilities.NormalizePath(intermediateDirectory); // If the intermediate directory ends up with a trailing slash, then be rid of it! if (FileUtilities.EndsWithSlash(intermediateDirectory)) { intermediateDirectory = Path.GetDirectoryName(intermediateDirectory); } builder.AppendSwitchIfNotNull("/i ", intermediateDirectory); } builder.AppendSwitchIfNotNull("/r ", rootFiles); builder.AppendSwitchIfNotNull("/b ", cancelEventName); // b for break return builder.ToString() + " "; } /// <summary> /// This method constructs the correct Tracker.exe command arguments from its parameters /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <returns>The arguments as a string</returns> public static string TrackerCommandArguments(string command, string arguments) { CommandLineBuilder builder = new CommandLineBuilder(); builder.AppendSwitch(" /c"); builder.AppendFileNameIfNotNull(command); string fullArguments = builder.ToString(); fullArguments += " " + arguments; return fullArguments; } /// <summary> /// This method constructs the correct Tracker.exe arguments from its parameters /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="dllName">The name of the dll that will do the tracking</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <returns>The arguments as a string</returns> public static string TrackerArguments(string command, string arguments, string dllName, string intermediateDirectory, string rootFiles) { return TrackerArguments(command, arguments, dllName, intermediateDirectory, rootFiles, null); } /// <summary> /// This method constructs the correct Tracker.exe arguments from its parameters /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="dllName">The name of the dll that will do the tracking</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <param name="cancelEventName">If a cancel event has been created that Tracker should be listening for, its name is passed here</param> /// <returns>The arguments as a string</returns> public static string TrackerArguments(string command, string arguments, string dllName, string intermediateDirectory, string rootFiles, string cancelEventName) { string fullArguments = TrackerResponseFileArguments(dllName, intermediateDirectory, rootFiles, cancelEventName); fullArguments += TrackerCommandArguments(command, arguments); return fullArguments; } #region StartProcess methods /// <summary> /// Start the process; tracking the command. /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="toolType">The type of executable the wrapped tool is</param> /// <param name="dllName">The name of the dll that will do the tracking</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <param name="cancelEventName">If Tracker should be listening on a particular event for cancellation, pass its name here</param> /// <returns>Process instance</returns> public static Process StartProcess(string command, string arguments, ExecutableType toolType, string dllName, string intermediateDirectory, string rootFiles, string cancelEventName) { dllName = dllName ?? GetFileTrackerPath(toolType); string fullArguments = TrackerArguments(command, arguments, dllName, intermediateDirectory, rootFiles, cancelEventName); return Process.Start(GetTrackerPath(toolType), fullArguments); } /// <summary> /// Start the process; tracking the command. /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="toolType">The type of executable the wrapped tool is</param> /// <param name="dllName">The name of the dll that will do the tracking</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <returns>Process instance</returns> public static Process StartProcess(string command, string arguments, ExecutableType toolType, string dllName, string intermediateDirectory, string rootFiles) { return StartProcess(command, arguments, toolType, dllName, intermediateDirectory, rootFiles, null); } /// <summary> /// Start the process; tracking the command. /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="toolType">The type of executable the wrapped tool is</param> /// <param name="intermediateDirectory">Intermediate directory where tracking logs will be written</param> /// <param name="rootFiles">Rooting marker</param> /// <returns>Process instance</returns> public static Process StartProcess(string command, string arguments, ExecutableType toolType, string intermediateDirectory, string rootFiles) { return StartProcess(command, arguments, toolType, null, intermediateDirectory, rootFiles, null); } /// <summary> /// Start the process; tracking the command. /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="toolType">The type of executable the wrapped tool is</param> /// <param name="rootFiles">Rooting marker</param> /// <returns>Process instance</returns> public static Process StartProcess(string command, string arguments, ExecutableType toolType, string rootFiles) { return StartProcess(command, arguments, toolType, null, null, rootFiles, null); } /// <summary> /// Start the process; tracking the command. /// </summary> /// <param name="command">The command to track</param> /// <param name="arguments">The command to track's arguments</param> /// <param name="toolType">The type of executable the wrapped tool is</param> /// <returns>Process instance</returns> public static Process StartProcess(string command, string arguments, ExecutableType toolType) { return StartProcess(command, arguments, toolType, null, null, null, null); } #endregion // StartProcess methods /// <summary> /// Logs a message of the given importance using the specified resource string. To the specified Log. /// </summary> /// <remarks>This method is not thread-safe.</remarks> /// <param name="Log">The Log to log to.</param> /// <param name="importance">The importance level of the message.</param> /// <param name="messageResourceName">The name of the string resource to load.</param> /// <param name="messageArgs">Optional arguments for formatting the loaded string.</param> /// <exception cref="ArgumentNullException">Thrown when <c>messageResourceName</c> is null.</exception> internal static void LogMessageFromResources(TaskLoggingHelper Log, MessageImportance importance, string messageResourceName, params object[] messageArgs) { // Only log when we have been passed a TaskLoggingHelper if (Log != null) { ErrorUtilities.VerifyThrowArgumentNull(messageResourceName, "messageResourceName"); Log.LogMessage(importance, AssemblyResources.FormatResourceString(messageResourceName, messageArgs)); } } /// <summary> /// Logs a message of the given importance using the specified string. /// </summary> /// <remarks>This method is not thread-safe.</remarks> /// <param name="importance">The importance level of the message.</param> /// <param name="message">The message string.</param> /// <param name="messageArgs">Optional arguments for formatting the message string.</param> /// <exception cref="ArgumentNullException">Thrown when <c>message</c> is null.</exception> internal static void LogMessage(TaskLoggingHelper Log, MessageImportance importance, string message, params object[] messageArgs) { // Only log when we have been passed a TaskLoggingHelper if (Log != null) { Log.LogMessage(importance, message, messageArgs); } } /// <summary> /// Logs a warning using the specified resource string. /// </summary> /// <param name="messageResourceName">The name of the string resource to load.</param> /// <param name="messageArgs">Optional arguments for formatting the loaded string.</param> /// <exception cref="ArgumentNullException">Thrown when <c>messageResourceName</c> is null.</exception> internal static void LogWarningWithCodeFromResources(TaskLoggingHelper Log, string messageResourceName, params object[] messageArgs) { // Only log when we have been passed a TaskLoggingHelper if (Log != null) { Log.LogWarningWithCodeFromResources(messageResourceName, messageArgs); } } #endregion } /// <summary> /// Dependency filter delegate. Used during TLog saves in order for tasks to selectively remove dependencies from the written /// graph. /// </summary> /// <param name="fullPath">The full path to the dependency file about to be written to the compacted TLog</param> /// <returns>If the file should actually be written to the TLog (true) or not (false)</returns> public delegate bool DependencyFilter(string fullPath); }
// // MultipartEncrypted.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013 Jeffrey Stedfast // // 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.IO; using System.Collections.Generic; using Org.BouncyCastle.Bcpg.OpenPgp; using MimeKit.IO; using MimeKit.IO.Filters; namespace MimeKit.Cryptography { /// <summary> /// A multipart MIME part with a ContentType of multipart/encrypted containing an encrypted MIME part. /// </summary> /// <remarks> /// This mime-type is common when dealing with PGP/MIME but is not used for S/MIME. /// </remarks> public class MultipartEncrypted : Multipart { /// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.MultipartEncrypted"/> class. /// </summary> /// <remarks>This constructor is used by <see cref="MimeKit.MimeParser"/>.</remarks> /// <param name="entity">Information used by the constructor.</param> public MultipartEncrypted (MimeEntityConstructorInfo entity) : base (entity) { } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.MultipartEncrypted"/> class. /// </summary> public MultipartEncrypted () : base ("encrypted") { } static void PrepareEntityForEncrypting (MimeEntity entity) { if (entity is Multipart) { // Note: we do not want to modify multipart/signed parts if (entity is MultipartSigned) return; var multipart = (Multipart) entity; foreach (var subpart in multipart) PrepareEntityForEncrypting (subpart); } else if (entity is MessagePart) { var mpart = (MessagePart) entity; if (mpart.Message != null && mpart.Message.Body != null) PrepareEntityForEncrypting (mpart.Message.Body); } else { var part = (MimePart) entity; if (part.ContentTransferEncoding == ContentEncoding.Binary) part.ContentTransferEncoding = ContentEncoding.Base64; else if (part.ContentTransferEncoding != ContentEncoding.Base64) part.ContentTransferEncoding = ContentEncoding.QuotedPrintable; } } /// <summary> /// Creates a new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance with the entity as the content. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing /// the signed and encrypted version of the specified entity.</returns> /// <param name="ctx">The OpenPGP cryptography context to use for signing and encrypting.</param> /// <param name="signer">The signer to use to sign the entity.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="recipients">The recipients for the encrypted entity.</param> /// <param name="entity">The entity to sign and encrypt.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="ctx"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="PrivateKeyNotFoundException"> /// The private key for <paramref name="signer"/> could not be found. /// </exception> /// <exception cref="PublicKeyNotFoundException"> /// A public key for one or more of the <paramref name="recipients"/> could not be found. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public static MultipartEncrypted Create (OpenPgpContext ctx, MailboxAddress signer, DigestAlgorithm digestAlgo, IEnumerable<MailboxAddress> recipients, MimeEntity entity) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (signer == null) throw new ArgumentNullException ("signer"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var memory = new MemoryStream ()) { var options = FormatOptions.Default.Clone (); options.NewLineFormat = NewLineFormat.Dos; PrepareEntityForEncrypting (entity); entity.WriteTo (options, memory); memory.Position = 0; var encrypted = new MultipartEncrypted (); encrypted.ContentType.Parameters["protocol"] = ctx.EncryptionProtocol; // add the protocol version part encrypted.Add (new ApplicationPgpEncrypted ()); // add the encrypted entity as the second part encrypted.Add (ctx.SignAndEncrypt (signer, digestAlgo, recipients, memory)); return encrypted; } } /// <summary> /// Creates a new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance with the entity as the content. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing /// the signed and encrypted version of the specified entity.</returns> /// <param name="signer">The signer to use to sign the entity.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="recipients">The recipients for the encrypted entity.</param> /// <param name="entity">The entity to sign and encrypt.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// A default <see cref="OpenPgpContext"/> has not been registered. /// </exception> /// <exception cref="PrivateKeyNotFoundException"> /// The private key for <paramref name="signer"/> could not be found. /// </exception> /// <exception cref="PublicKeyNotFoundException"> /// A public key for one or more of the <paramref name="recipients"/> could not be found. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public static MultipartEncrypted Create (MailboxAddress signer, DigestAlgorithm digestAlgo, IEnumerable<MailboxAddress> recipients, MimeEntity entity) { if (signer == null) throw new ArgumentNullException ("signer"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var ctx = (OpenPgpContext) CryptographyContext.Create ("application/pgp-encrypted")) { return Create (ctx, signer, digestAlgo, recipients, entity); } } /// <summary> /// Creates a new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance with the entity as the content. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing /// the signed and encrypted version of the specified entity.</returns> /// <param name="ctx">The OpenPGP cryptography context to use for singing and encrypting.</param> /// <param name="signer">The signer to use to sign the entity.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="recipients">The recipients for the encrypted entity.</param> /// <param name="entity">The entity to sign and encrypt.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="ctx"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="signer"/> cannot be used for signing.</para> /// <para>-or-</para> /// <para>One or more of the recipient keys cannot be used for encrypting.</para> /// <para>-or-</para> /// <para>No recipients were specified.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// The <paramref name="digestAlgo"/> was out of range. /// </exception> /// <exception cref="System.NotSupportedException"> /// The <paramref name="digestAlgo"/> is not supported. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public static MultipartEncrypted Create (OpenPgpContext ctx, PgpSecretKey signer, DigestAlgorithm digestAlgo, IEnumerable<PgpPublicKey> recipients, MimeEntity entity) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (signer == null) throw new ArgumentNullException ("signer"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var memory = new MemoryStream ()) { var options = FormatOptions.Default.Clone (); options.NewLineFormat = NewLineFormat.Dos; PrepareEntityForEncrypting (entity); entity.WriteTo (options, memory); memory.Position = 0; var encrypted = new MultipartEncrypted (); encrypted.ContentType.Parameters["protocol"] = ctx.EncryptionProtocol; // add the protocol version part encrypted.Add (new ApplicationPgpEncrypted ()); // add the encrypted entity as the second part encrypted.Add (ctx.SignAndEncrypt (signer, digestAlgo, recipients, memory)); return encrypted; } } /// <summary> /// Creates a new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance with the entity as the content. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing /// the signed and encrypted version of the specified entity.</returns> /// <param name="signer">The signer to use to sign the entity.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="recipients">The recipients for the encrypted entity.</param> /// <param name="entity">The entity to sign and encrypt.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="signer"/> cannot be used for signing.</para> /// <para>-or-</para> /// <para>One or more of the recipient keys cannot be used for encrypting.</para> /// <para>-or-</para> /// <para>No recipients were specified.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// The <paramref name="digestAlgo"/> was out of range. /// </exception> /// <exception cref="System.NotSupportedException"> /// <para>A default <see cref="OpenPgpContext"/> has not been registered.</para> /// <para>-or-</para> /// <para>The <paramref name="digestAlgo"/> is not supported.</para> /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public static MultipartEncrypted Create (PgpSecretKey signer, DigestAlgorithm digestAlgo, IEnumerable<PgpPublicKey> recipients, MimeEntity entity) { if (signer == null) throw new ArgumentNullException ("signer"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var ctx = (OpenPgpContext) CryptographyContext.Create ("application/pgp-encrypted")) { return Create (ctx, signer, digestAlgo, recipients, entity); } } /// <summary> /// Creates a new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance with the entity as the content. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing /// the encrypted version of the specified entity.</returns> /// <param name="ctx">The OpenPGP cryptography context to use for encrypting.</param> /// <param name="recipients">The recipients for the encrypted entity.</param> /// <param name="entity">The entity to sign and encrypt.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="ctx"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="PublicKeyNotFoundException"> /// A public key for one or more of the <paramref name="recipients"/> could not be found. /// </exception> public static MultipartEncrypted Create (OpenPgpContext ctx, IEnumerable<MailboxAddress> recipients, MimeEntity entity) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var memory = new MemoryStream ()) { using (var filtered = new FilteredStream (memory)) { filtered.Add (new Unix2DosFilter ()); PrepareEntityForEncrypting (entity); entity.WriteTo (filtered); filtered.Flush (); } memory.Position = 0; var encrypted = new MultipartEncrypted (); encrypted.ContentType.Parameters["protocol"] = ctx.EncryptionProtocol; // add the protocol version part encrypted.Add (new ApplicationPgpEncrypted ()); // add the encrypted entity as the second part encrypted.Add (ctx.Encrypt (recipients, memory)); return encrypted; } } /// <summary> /// Creates a new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance with the entity as the content. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing /// the encrypted version of the specified entity.</returns> /// <param name="recipients">The recipients for the encrypted entity.</param> /// <param name="entity">The entity to sign and encrypt.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// A default <see cref="OpenPgpContext"/> has not been registered. /// </exception> /// <exception cref="PublicKeyNotFoundException"> /// A public key for one or more of the <paramref name="recipients"/> could not be found. /// </exception> public static MultipartEncrypted Create (IEnumerable<MailboxAddress> recipients, MimeEntity entity) { if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var ctx = (OpenPgpContext) CryptographyContext.Create ("application/pgp-encrypted")) { return Create (ctx, recipients, entity); } } /// <summary> /// Creates a new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance with the entity as the content. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing /// the encrypted version of the specified entity.</returns> /// <param name="ctx">The OpenPGP cryptography context to use for encrypting.</param> /// <param name="recipients">The recipients for the encrypted entity.</param> /// <param name="entity">The entity to sign and encrypt.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="ctx"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// One or more of the recipient keys cannot be used for encrypting. /// </exception> public static MultipartEncrypted Create (OpenPgpContext ctx, IEnumerable<PgpPublicKey> recipients, MimeEntity entity) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var memory = new MemoryStream ()) { using (var filtered = new FilteredStream (memory)) { filtered.Add (new Unix2DosFilter ()); PrepareEntityForEncrypting (entity); entity.WriteTo (filtered); filtered.Flush (); } memory.Position = 0; var encrypted = new MultipartEncrypted (); encrypted.ContentType.Parameters["protocol"] = ctx.EncryptionProtocol; // add the protocol version part encrypted.Add (new ApplicationPgpEncrypted ()); // add the encrypted entity as the second part encrypted.Add (ctx.Encrypt (recipients, memory)); return encrypted; } } /// <summary> /// Creates a new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance with the entity as the content. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing /// the encrypted version of the specified entity.</returns> /// <param name="recipients">The recipients for the encrypted entity.</param> /// <param name="entity">The entity to sign and encrypt.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// One or more of the recipient keys cannot be used for encrypting. /// </exception> /// <exception cref="System.NotSupportedException"> /// A default <see cref="OpenPgpContext"/> has not been registered. /// </exception> public static MultipartEncrypted Create (IEnumerable<PgpPublicKey> recipients, MimeEntity entity) { if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var ctx = (OpenPgpContext) CryptographyContext.Create ("application/pgp-encrypted")) { return Create (ctx, recipients, entity); } } /// <summary> /// Decrypt this instance. /// </summary> /// <returns>The decrypted entity.</returns> /// <param name="ctx">The OpenPGP cryptography context to use for decrypting.</param> /// <param name="signatures">A list of digital signatures if the data was both signed and encrypted.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="ctx"/> is <c>null</c>. /// </exception> /// <exception cref="System.FormatException"> /// <para>The <c>protocol</c> parameter was not specified.</para> /// <para>-or-</para> /// <para>The multipart is malformed in some way.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// The provided <see cref="OpenPgpContext"/> does not support the protocol parameter. /// </exception> /// <exception cref="PrivateKeyNotFoundException"> /// The private key could not be found to decrypt the encrypted data. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public MimeEntity Decrypt (OpenPgpContext ctx, out DigitalSignatureCollection signatures) { if (ctx == null) throw new ArgumentNullException ("ctx"); var protocol = ContentType.Parameters["protocol"]; if (string.IsNullOrEmpty (protocol)) throw new FormatException (); protocol = protocol.Trim ().ToLowerInvariant (); if (!ctx.Supports (protocol)) throw new NotSupportedException (); if (Count < 2) throw new FormatException (); var version = this[0] as MimePart; if (version == null) throw new FormatException (); var ctype = version.ContentType; var value = string.Format ("{0}/{1}", ctype.MediaType, ctype.MediaSubtype); if (value.ToLowerInvariant () != protocol) throw new FormatException (); var encrypted = this[1] as MimePart; if (encrypted == null || encrypted.ContentObject == null) throw new FormatException (); if (!encrypted.ContentType.Matches ("application", "octet-stream")) throw new FormatException (); using (var memory = new MemoryStream ()) { encrypted.ContentObject.DecodeTo (memory); memory.Position = 0; return ctx.Decrypt (memory, out signatures); } } /// <summary> /// Decrypt this instance. /// </summary> /// <returns>The decrypted entity.</returns> /// <param name="ctx">The OpenPGP cryptography context to use for decrypting.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="ctx"/> is <c>null</c>. /// </exception> /// <exception cref="System.FormatException"> /// <para>The <c>protocol</c> parameter was not specified.</para> /// <para>-or-</para> /// <para>The multipart is malformed in some way.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// The provided <see cref="OpenPgpContext"/> does not support the protocol parameter. /// </exception> /// <exception cref="PrivateKeyNotFoundException"> /// The private key could not be found to decrypt the encrypted data. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public MimeEntity Decrypt (OpenPgpContext ctx) { DigitalSignatureCollection signatures; return Decrypt (ctx, out signatures); } /// <summary> /// Decrypt this instance. /// </summary> /// <returns>The decrypted entity.</returns> /// <param name="signatures">A list of digital signatures if the data was both signed and encrypted.</param> /// <exception cref="System.FormatException"> /// <para>The <c>protocol</c> parameter was not specified.</para> /// <para>-or-</para> /// <para>The multipart is malformed in some way.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// A suitable <see cref="MimeKit.Cryptography.CryptographyContext"/> for /// decrypting could not be found. /// </exception> /// <exception cref="PrivateKeyNotFoundException"> /// The private key could not be found to decrypt the encrypted data. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public MimeEntity Decrypt (out DigitalSignatureCollection signatures) { var protocol = ContentType.Parameters["protocol"]; if (string.IsNullOrEmpty (protocol)) throw new FormatException (); protocol = protocol.Trim ().ToLowerInvariant (); if (Count < 2) throw new FormatException (); var version = this[0] as MimePart; if (version == null) throw new FormatException (); var ctype = version.ContentType; var value = string.Format ("{0}/{1}", ctype.MediaType, ctype.MediaSubtype); if (value.ToLowerInvariant () != protocol) throw new FormatException (); var encrypted = this[1] as MimePart; if (encrypted == null || encrypted.ContentObject == null) throw new FormatException (); if (!encrypted.ContentType.Matches ("application", "octet-stream")) throw new FormatException (); using (var ctx = CryptographyContext.Create (protocol)) { using (var memory = new MemoryStream ()) { var pgp = ctx as OpenPgpContext; encrypted.ContentObject.DecodeTo (memory); memory.Position = 0; if (pgp != null) return pgp.Decrypt (memory, out signatures); signatures = null; return ctx.Decrypt (memory); } } } /// <summary> /// Decrypt this instance. /// </summary> /// <returns>The decrypted entity.</returns> /// <exception cref="System.FormatException"> /// <para>The <c>protocol</c> parameter was not specified.</para> /// <para>-or-</para> /// <para>The multipart is malformed in some way.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// A suitable <see cref="MimeKit.Cryptography.CryptographyContext"/> for /// decrypting could not be found. /// </exception> /// <exception cref="PrivateKeyNotFoundException"> /// The private key could not be found to decrypt the encrypted data. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The user chose to cancel the password prompt. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// 3 bad attempts were made to unlock the secret key. /// </exception> public MimeEntity Decrypt () { DigitalSignatureCollection signatures; return Decrypt (out signatures); } } }
/* * 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.Reflection; using log4net; using Mono.Addins; namespace OpenSim.Framework { /// <summary> /// Exception thrown if an incorrect number of plugins are loaded /// </summary> public class PluginConstraintViolatedException : Exception { public PluginConstraintViolatedException () : base() {} public PluginConstraintViolatedException (string msg) : base(msg) {} public PluginConstraintViolatedException (string msg, Exception e) : base(msg, e) {} } /// <summary> /// Classes wishing to impose constraints on plugin loading must implement /// this class and pass it to PluginLoader AddConstraint() /// </summary> public interface IPluginConstraint { string Message { get; } bool Apply(string extpoint); } /// <summary> /// Classes wishing to select specific plugins from a range of possible options /// must implement this class and pass it to PluginLoader Load() /// </summary> public interface IPluginFilter { bool Apply(PluginExtensionNode plugin); } /// <summary> /// Generic Plugin Loader /// </summary> public class PluginLoader <T> : IDisposable where T : IPlugin { private const int max_loadable_plugins = 10000; private List<T> loaded = new List<T>(); private List<string> extpoints = new List<string>(); private PluginInitializerBase initializer; private Dictionary<string,IPluginConstraint> constraints = new Dictionary<string,IPluginConstraint>(); private Dictionary<string,IPluginFilter> filters = new Dictionary<string,IPluginFilter>(); private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public PluginInitializerBase Initializer { set { initializer = value; } get { return initializer; } } public List<T> Plugins { get { return loaded; } } public T Plugin { get { return (loaded.Count == 1)? loaded [0] : default (T); } } public PluginLoader() { Initializer = new PluginInitializerBase(); initialize_plugin_dir_("."); } public PluginLoader(PluginInitializerBase init) { Initializer = init; initialize_plugin_dir_("."); } public PluginLoader(PluginInitializerBase init, string dir) { Initializer = init; initialize_plugin_dir_(dir); } public void Add(string extpoint) { if (extpoints.Contains(extpoint)) return; extpoints.Add(extpoint); } public void Add(string extpoint, IPluginConstraint cons) { Add(extpoint); AddConstraint(extpoint, cons); } public void Add(string extpoint, IPluginFilter filter) { Add(extpoint); AddFilter(extpoint, filter); } public void AddConstraint(string extpoint, IPluginConstraint cons) { constraints.Add(extpoint, cons); } public void AddFilter(string extpoint, IPluginFilter filter) { filters.Add(extpoint, filter); } public void Load(string extpoint) { Add(extpoint); Load(); } public void Load() { foreach (string ext in extpoints) { log.Info("[PLUGINS]: Loading extension point " + ext); if (constraints.ContainsKey(ext)) { IPluginConstraint cons = constraints[ext]; if (cons.Apply(ext)) log.Error("[PLUGINS]: " + ext + " failed constraint: " + cons.Message); } IPluginFilter filter = null; if (filters.ContainsKey(ext)) filter = filters[ext]; List<T> loadedPlugins = new List<T>(); foreach (PluginExtensionNode node in AddinManager.GetExtensionNodes(ext)) { log.Info("[PLUGINS]: Trying plugin " + node.Path); if ((filter != null) && (filter.Apply(node) == false)) continue; T plugin = (T)node.CreateInstance(); loadedPlugins.Add(plugin); } // We do Initialize() in a second loop after CreateInstance // So that modules who need init before others can do it // Example: Script Engine Component System needs to load its components before RegionLoader starts foreach (T plugin in loadedPlugins) { Initializer.Initialize(plugin); Plugins.Add(plugin); } } } public void Dispose() { foreach (T plugin in Plugins) plugin.Dispose(); } private void initialize_plugin_dir_(string dir) { if (AddinManager.IsInitialized == true) return; log.Info("[PLUGINS]: Initializing addin manager"); AddinManager.AddinLoadError += on_addinloaderror_; AddinManager.AddinLoaded += on_addinloaded_; if (System.Diagnostics.Process.GetCurrentProcess().ProcessName.Contains("OpenSim.Grid.UserServer")) { log.Info("[PLUGINS]: Cleaning out addins directory"); clear_registry_(); } suppress_console_output_(true); Directory.CreateDirectory("addin-db-001/addin-dir-data"); AddinManager.Initialize(dir); AddinManager.Registry.Update(null); suppress_console_output_(false); } private void on_addinloaded_(object sender, AddinEventArgs args) { log.Info ("[PLUGINS]: Plugin Loaded: " + args.AddinId); } private void on_addinloaderror_(object sender, AddinErrorEventArgs args) { if (args.Exception == null) log.Error ("[PLUGINS]: Plugin Error: " + args.Message); else log.Error ("[PLUGINS]: Plugin Error: " + args.Exception.Message + "\n" + args.Exception.StackTrace); } private void clear_registry_() { // The Mono addin manager (in Mono.Addins.dll version 0.2.0.0) // occasionally seems to corrupt its addin cache // Hence, as a temporary solution we'll remove it before each startup try { if (Directory.Exists("addin-db-000")) Directory.Delete("addin-db-000", true); if (Directory.Exists("addin-db-001")) Directory.Delete("addin-db-001", true); } catch (IOException) { // If multiple services are started simultaneously, they may // each test whether the directory exists at the same time, and // attempt to delete the directory at the same time. However, // one of the services will likely succeed first, causing the // second service to throw an IOException. We catch it here and // continue on our merry way. // Mike 2008.08.01, patch from Zaki } } private static TextWriter prev_console_; public void suppress_console_output_(bool save) { if (save) { prev_console_ = System.Console.Out; System.Console.SetOut(new StreamWriter(Stream.Null)); } else { if (prev_console_ != null) System.Console.SetOut(prev_console_); } } } public class PluginExtensionNode : ExtensionNode { [NodeAttribute] string id = String.Empty; [NodeAttribute] string provider = String.Empty; [NodeAttribute] string type = String.Empty; Type typeobj; public string ID { get { return id; } } public string Provider { get { return provider; } } public string TypeName { get { return type; } } public Type TypeObject { get { if (typeobj != null) return typeobj; if (String.IsNullOrEmpty(type)) throw new InvalidOperationException("Type name not specified."); return typeobj = Addin.GetType(type, true); } } public object CreateInstance() { return Activator.CreateInstance(TypeObject); } } /// <summary> /// Constraint that bounds the number of plugins to be loaded. /// </summary> public class PluginCountConstraint : IPluginConstraint { private int min; private int max; public PluginCountConstraint(int exact) { min = exact; max = exact; } public PluginCountConstraint(int minimum, int maximum) { min = minimum; max = maximum; } public string Message { get { return "The number of plugins is constrained to the interval [" + min + ", " + max + "]"; } } public bool Apply (string extpoint) { int count = AddinManager.GetExtensionNodes(extpoint).Count; if ((count < min) || (count > max)) throw new PluginConstraintViolatedException(Message); return true; } } /// <summary> /// Filters out which plugin to load based on the plugin name or names given. Plugin names are contained in /// their addin.xml /// </summary> public class PluginProviderFilter : IPluginFilter { private string[] m_filters; /// <summary> /// Constructor. /// </summary> /// <param name="p"> /// Plugin name or names on which to filter. Multiple names should be separated by commas. /// </param> public PluginProviderFilter(string p) { m_filters = p.Split(','); for (int i = 0; i < m_filters.Length; i++) { m_filters[i] = m_filters[i].Trim(); } } /// <summary> /// Apply this filter to the given plugin. /// </summary> /// <param name="plugin"></param> /// <returns>true if the plugin's name matched one of the filters, false otherwise.</returns> public bool Apply (PluginExtensionNode plugin) { for (int i = 0; i < m_filters.Length; i++) { if (m_filters[i] == plugin.Provider) { return true; } } return false; } } /// <summary> /// Filters plugins according to their ID. Plugin IDs are contained in their addin.xml /// </summary> public class PluginIdFilter : IPluginFilter { private string[] m_filters; /// <summary> /// Constructor. /// </summary> /// <param name="p"> /// Plugin ID or IDs on which to filter. Multiple names should be separated by commas. /// </param> public PluginIdFilter(string p) { m_filters = p.Split(','); for (int i = 0; i < m_filters.Length; i++) { m_filters[i] = m_filters[i].Trim(); } } /// <summary> /// Apply this filter to <paramref name="plugin" />. /// </summary> /// <param name="plugin">PluginExtensionNode instance to check whether it passes the filter.</param> /// <returns>true if the plugin's ID matches one of the filters, false otherwise.</returns> public bool Apply (PluginExtensionNode plugin) { for (int i = 0; i < m_filters.Length; i++) { if (m_filters[i] == plugin.ID) { return true; } } return false; } } }
// ReSharper disable CheckNamespace #pragma warning disable 1591 using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using GSF.ComponentModel; using GSF.ComponentModel.DataAnnotations; using GSF.Data.Model; namespace openPDC.Model { [PrimaryLabel("Acronym")] public class Device { [DefaultValueExpression("Global.NodeID")] public Guid NodeID { get; set; } [Label("Local Device ID")] [PrimaryKey(true)] public int ID { get; set; } public int? ParentID { get; set; } [Label("Unique Device ID")] [DefaultValueExpression("Guid.NewGuid()")] public Guid UniqueID { get; set; } [Required] [StringLength(200)] [AcronymValidation] [Searchable] public string Acronym { get; set; } [StringLength(200)] public string Name { get; set; } [Label("Folder Name")] [StringLength(20)] public string OriginalSource { get; set; } [Label("Is Concentrator")] public bool IsConcentrator { get; set; } [Required] [Label("Company")] [DefaultValueExpression("Connection.ExecuteScalar(typeof(int), (object)null, 'SELECT ID FROM Company WHERE Acronym = {0}', Global.CompanyAcronym)", Cached = true)] public int? CompanyID { get; set; } [Label("Historian")] public int? HistorianID { get; set; } [Label("Access ID")] public int AccessID { get; set; } [Label("Vendor Device")] public int? VendorDeviceID { get; set; } [Label("Protocol")] public int? ProtocolID { get; set; } public decimal? Longitude { get; set; } public decimal? Latitude { get; set; } [Label("Interconnection")] [InitialValueScript("1")] public int? InterconnectionID { get; set; } [Label("Connection String")] public string ConnectionString { get; set; } [StringLength(200)] public string TimeZone { get; set; } [Label("Frames Per Second")] [DefaultValue(30)] public int? FramesPerSecond { get; set; } public long TimeAdjustmentTicks { get; set; } [DefaultValue(5.0D)] public double DataLossInterval { get; set; } [DefaultValue(10)] public int AllowedParsingExceptions { get; set; } [DefaultValue(5.0D)] public double ParsingExceptionWindow { get; set; } [DefaultValue(5.0D)] public double DelayedConnectionInterval { get; set; } [DefaultValue(true)] public bool AllowUseOfCachedConfiguration { get; set; } [DefaultValue(true)] public bool AutoStartDataParsingSequence { get; set; } public bool SkipDisableRealTimeData { get; set; } [DefaultValue(100000)] public int MeasurementReportingInterval { get; set; } [Label("Connect On Demand")] [DefaultValue(true)] public bool ConnectOnDemand { get; set; } [Label("Contacts")] public string ContactList { get; set; } public int? MeasuredLines { get; set; } public int LoadOrder { get; set; } public bool Enabled { get; set; } /// <summary> /// Created on field. /// </summary> [DefaultValueExpression("DateTime.UtcNow")] public DateTime CreatedOn { get; set; } /// <summary> /// Created by field. /// </summary> [Required] [StringLength(50)] [DefaultValueExpression("UserInfo.CurrentUserID")] public string CreatedBy { get; set; } /// <summary> /// Updated on field. /// </summary> [DefaultValueExpression("this.CreatedOn", EvaluationOrder = 1)] [UpdateValueExpression("DateTime.UtcNow")] public DateTime UpdatedOn { get; set; } /// <summary> /// Updated by field. /// </summary> [Required] [StringLength(50)] [DefaultValueExpression("this.CreatedBy", EvaluationOrder = 1)] [UpdateValueExpression("UserInfo.CurrentUserID")] public string UpdatedBy { get; set; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="AdParameterServiceClient"/> instances.</summary> public sealed partial class AdParameterServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AdParameterServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AdParameterServiceSettings"/>.</returns> public static AdParameterServiceSettings GetDefault() => new AdParameterServiceSettings(); /// <summary>Constructs a new <see cref="AdParameterServiceSettings"/> object with default settings.</summary> public AdParameterServiceSettings() { } private AdParameterServiceSettings(AdParameterServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetAdParameterSettings = existing.GetAdParameterSettings; MutateAdParametersSettings = existing.MutateAdParametersSettings; OnCopy(existing); } partial void OnCopy(AdParameterServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdParameterServiceClient.GetAdParameter</c> and <c>AdParameterServiceClient.GetAdParameterAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetAdParameterSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdParameterServiceClient.MutateAdParameters</c> and <c>AdParameterServiceClient.MutateAdParametersAsync</c> /// . /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateAdParametersSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="AdParameterServiceSettings"/> object.</returns> public AdParameterServiceSettings Clone() => new AdParameterServiceSettings(this); } /// <summary> /// Builder class for <see cref="AdParameterServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class AdParameterServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdParameterServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AdParameterServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AdParameterServiceClientBuilder() { UseJwtAccessWithScopes = AdParameterServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AdParameterServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdParameterServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AdParameterServiceClient Build() { AdParameterServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AdParameterServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AdParameterServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AdParameterServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AdParameterServiceClient.Create(callInvoker, Settings); } private async stt::Task<AdParameterServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AdParameterServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AdParameterServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdParameterServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AdParameterServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>AdParameterService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage ad parameters. /// </remarks> public abstract partial class AdParameterServiceClient { /// <summary> /// The default endpoint for the AdParameterService service, which is a host of "googleads.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default AdParameterService scopes.</summary> /// <remarks> /// The default AdParameterService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="AdParameterServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="AdParameterServiceClientBuilder"/> /// . /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AdParameterServiceClient"/>.</returns> public static stt::Task<AdParameterServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AdParameterServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AdParameterServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="AdParameterServiceClientBuilder"/> /// . /// </summary> /// <returns>The created <see cref="AdParameterServiceClient"/>.</returns> public static AdParameterServiceClient Create() => new AdParameterServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AdParameterServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="AdParameterServiceSettings"/>.</param> /// <returns>The created <see cref="AdParameterServiceClient"/>.</returns> internal static AdParameterServiceClient Create(grpccore::CallInvoker callInvoker, AdParameterServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AdParameterService.AdParameterServiceClient grpcClient = new AdParameterService.AdParameterServiceClient(callInvoker); return new AdParameterServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC AdParameterService client</summary> public virtual AdParameterService.AdParameterServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad parameter in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdParameter GetAdParameter(GetAdParameterRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad parameter in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdParameter> GetAdParameterAsync(GetAdParameterRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad parameter in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdParameter> GetAdParameterAsync(GetAdParameterRequest request, st::CancellationToken cancellationToken) => GetAdParameterAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested ad parameter in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad parameter to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdParameter GetAdParameter(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdParameter(new GetAdParameterRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad parameter in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad parameter to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdParameter> GetAdParameterAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdParameterAsync(new GetAdParameterRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad parameter in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad parameter to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdParameter> GetAdParameterAsync(string resourceName, st::CancellationToken cancellationToken) => GetAdParameterAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested ad parameter in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad parameter to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdParameter GetAdParameter(gagvr::AdParameterName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdParameter(new GetAdParameterRequest { ResourceNameAsAdParameterName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad parameter in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad parameter to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdParameter> GetAdParameterAsync(gagvr::AdParameterName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdParameterAsync(new GetAdParameterRequest { ResourceNameAsAdParameterName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad parameter in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad parameter to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdParameter> GetAdParameterAsync(gagvr::AdParameterName resourceName, st::CancellationToken cancellationToken) => GetAdParameterAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes ad parameters. Operation statuses are /// returned. /// /// List of thrown errors: /// [AdParameterError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdParametersResponse MutateAdParameters(MutateAdParametersRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad parameters. Operation statuses are /// returned. /// /// List of thrown errors: /// [AdParameterError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdParametersResponse> MutateAdParametersAsync(MutateAdParametersRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad parameters. Operation statuses are /// returned. /// /// List of thrown errors: /// [AdParameterError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdParametersResponse> MutateAdParametersAsync(MutateAdParametersRequest request, st::CancellationToken cancellationToken) => MutateAdParametersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes ad parameters. Operation statuses are /// returned. /// /// List of thrown errors: /// [AdParameterError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad parameters are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad parameters. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdParametersResponse MutateAdParameters(string customerId, scg::IEnumerable<AdParameterOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdParameters(new MutateAdParametersRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad parameters. Operation statuses are /// returned. /// /// List of thrown errors: /// [AdParameterError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad parameters are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad parameters. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdParametersResponse> MutateAdParametersAsync(string customerId, scg::IEnumerable<AdParameterOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdParametersAsync(new MutateAdParametersRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad parameters. Operation statuses are /// returned. /// /// List of thrown errors: /// [AdParameterError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad parameters are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad parameters. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdParametersResponse> MutateAdParametersAsync(string customerId, scg::IEnumerable<AdParameterOperation> operations, st::CancellationToken cancellationToken) => MutateAdParametersAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AdParameterService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage ad parameters. /// </remarks> public sealed partial class AdParameterServiceClientImpl : AdParameterServiceClient { private readonly gaxgrpc::ApiCall<GetAdParameterRequest, gagvr::AdParameter> _callGetAdParameter; private readonly gaxgrpc::ApiCall<MutateAdParametersRequest, MutateAdParametersResponse> _callMutateAdParameters; /// <summary> /// Constructs a client wrapper for the AdParameterService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="AdParameterServiceSettings"/> used within this client.</param> public AdParameterServiceClientImpl(AdParameterService.AdParameterServiceClient grpcClient, AdParameterServiceSettings settings) { GrpcClient = grpcClient; AdParameterServiceSettings effectiveSettings = settings ?? AdParameterServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetAdParameter = clientHelper.BuildApiCall<GetAdParameterRequest, gagvr::AdParameter>(grpcClient.GetAdParameterAsync, grpcClient.GetAdParameter, effectiveSettings.GetAdParameterSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetAdParameter); Modify_GetAdParameterApiCall(ref _callGetAdParameter); _callMutateAdParameters = clientHelper.BuildApiCall<MutateAdParametersRequest, MutateAdParametersResponse>(grpcClient.MutateAdParametersAsync, grpcClient.MutateAdParameters, effectiveSettings.MutateAdParametersSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateAdParameters); Modify_MutateAdParametersApiCall(ref _callMutateAdParameters); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetAdParameterApiCall(ref gaxgrpc::ApiCall<GetAdParameterRequest, gagvr::AdParameter> call); partial void Modify_MutateAdParametersApiCall(ref gaxgrpc::ApiCall<MutateAdParametersRequest, MutateAdParametersResponse> call); partial void OnConstruction(AdParameterService.AdParameterServiceClient grpcClient, AdParameterServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AdParameterService client</summary> public override AdParameterService.AdParameterServiceClient GrpcClient { get; } partial void Modify_GetAdParameterRequest(ref GetAdParameterRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateAdParametersRequest(ref MutateAdParametersRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested ad parameter in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::AdParameter GetAdParameter(GetAdParameterRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdParameterRequest(ref request, ref callSettings); return _callGetAdParameter.Sync(request, callSettings); } /// <summary> /// Returns the requested ad parameter in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::AdParameter> GetAdParameterAsync(GetAdParameterRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdParameterRequest(ref request, ref callSettings); return _callGetAdParameter.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes ad parameters. Operation statuses are /// returned. /// /// List of thrown errors: /// [AdParameterError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateAdParametersResponse MutateAdParameters(MutateAdParametersRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdParametersRequest(ref request, ref callSettings); return _callMutateAdParameters.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes ad parameters. Operation statuses are /// returned. /// /// List of thrown errors: /// [AdParameterError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateAdParametersResponse> MutateAdParametersAsync(MutateAdParametersRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdParametersRequest(ref request, ref callSettings); return _callMutateAdParameters.Async(request, callSettings); } } }
// // 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.Text; using Mono.Cecil.Metadata; namespace Mono.Cecil { class TypeParser { class Type { public const int Ptr = -1; public const int ByRef = -2; public const int SzArray = -3; public string type_fullname; public string [] nested_names; public int arity; public int [] specs; public Type [] generic_arguments; public string assembly; } readonly string fullname; readonly int length; int position; TypeParser (string fullname) { this.fullname = fullname; this.length = fullname.Length; } Type ParseType (bool fq_name) { var type = new Type (); type.type_fullname = ParsePart (); type.nested_names = ParseNestedNames (); if (TryGetArity (type)) type.generic_arguments = ParseGenericArguments (type.arity); type.specs = ParseSpecs (); if (fq_name) type.assembly = ParseAssemblyName (); return type; } static bool TryGetArity (Type type) { int arity = 0; TryAddArity (type.type_fullname, ref arity); var nested_names = type.nested_names; if (!nested_names.IsNullOrEmpty ()) { for (int i = 0; i < nested_names.Length; i++) TryAddArity (nested_names [i], ref arity); } type.arity = arity; return arity > 0; } static bool TryGetArity (string name, out int arity) { arity = 0; var index = name.LastIndexOf ('`'); if (index == -1) return false; return ParseInt32 (name.Substring (index + 1), out arity); } static bool ParseInt32 (string value, out int result) { return int.TryParse (value, out result); } static void TryAddArity (string name, ref int arity) { int type_arity; if (!TryGetArity (name, out type_arity)) return; arity += type_arity; } string ParsePart () { var part = new StringBuilder (); while (position < length && !IsDelimiter (fullname [position])) { if (fullname [position] == '\\') position++; part.Append (fullname [position++]); } return part.ToString (); } static bool IsDelimiter (char chr) { return "+,[]*&".IndexOf (chr) != -1; } void TryParseWhiteSpace () { while (position < length && Char.IsWhiteSpace (fullname [position])) position++; } string [] ParseNestedNames () { string [] nested_names = null; while (TryParse ('+')) Add (ref nested_names, ParsePart ()); return nested_names; } bool TryParse (char chr) { if (position < length && fullname [position] == chr) { position++; return true; } return false; } static void Add<T> (ref T [] array, T item) { array = array.Add (item); } int [] ParseSpecs () { int [] specs = null; while (position < length) { switch (fullname [position]) { case '*': position++; Add (ref specs, Type.Ptr); break; case '&': position++; Add (ref specs, Type.ByRef); break; case '[': position++; switch (fullname [position]) { case ']': position++; Add (ref specs, Type.SzArray); break; case '*': position++; Add (ref specs, 1); break; default: var rank = 1; while (TryParse (',')) rank++; Add (ref specs, rank); TryParse (']'); break; } break; default: return specs; } } return specs; } Type [] ParseGenericArguments (int arity) { Type [] generic_arguments = null; if (position == length || fullname [position] != '[') return generic_arguments; TryParse ('['); for (int i = 0; i < arity; i++) { var fq_argument = TryParse ('['); Add (ref generic_arguments, ParseType (fq_argument)); if (fq_argument) TryParse (']'); TryParse (','); TryParseWhiteSpace (); } TryParse (']'); return generic_arguments; } string ParseAssemblyName () { if (!TryParse (',')) return string.Empty; TryParseWhiteSpace (); var start = position; while (position < length) { var chr = fullname [position]; if (chr == '[' || chr == ']') break; position++; } return fullname.Substring (start, position - start); } public static TypeReference ParseType (ModuleDefinition module, string fullname, bool typeDefinitionOnly = false) { if (string.IsNullOrEmpty (fullname)) return null; var parser = new TypeParser (fullname); return GetTypeReference (module, parser.ParseType (true), typeDefinitionOnly); } static TypeReference GetTypeReference (ModuleDefinition module, Type type_info, bool type_def_only) { TypeReference type; if (!TryGetDefinition (module, type_info, out type)) { if (type_def_only) return null; type = CreateReference (type_info, module, GetMetadataScope (module, type_info)); } return CreateSpecs (type, type_info); } static TypeReference CreateSpecs (TypeReference type, Type type_info) { type = TryCreateGenericInstanceType (type, type_info); var specs = type_info.specs; if (specs.IsNullOrEmpty ()) return type; for (int i = 0; i < specs.Length; i++) { switch (specs [i]) { case Type.Ptr: type = new PointerType (type); break; case Type.ByRef: type = new ByReferenceType (type); break; case Type.SzArray: type = new ArrayType (type); break; default: var array = new ArrayType (type); array.Dimensions.Clear (); for (int j = 0; j < specs [i]; j++) array.Dimensions.Add (new ArrayDimension ()); type = array; break; } } return type; } static TypeReference TryCreateGenericInstanceType (TypeReference type, Type type_info) { var generic_arguments = type_info.generic_arguments; if (generic_arguments.IsNullOrEmpty ()) return type; var instance = new GenericInstanceType (type); var instance_arguments = instance.GenericArguments; for (int i = 0; i < generic_arguments.Length; i++) instance_arguments.Add (GetTypeReference (type.Module, generic_arguments [i], false)); return instance; } public static void SplitFullName (string fullname, out string @namespace, out string name) { var last_dot = fullname.LastIndexOf ('.'); if (last_dot == -1) { @namespace = string.Empty; name = fullname; } else { @namespace = fullname.Substring (0, last_dot); name = fullname.Substring (last_dot + 1); } } static TypeReference CreateReference (Type type_info, ModuleDefinition module, IMetadataScope scope) { string @namespace, name; SplitFullName (type_info.type_fullname, out @namespace, out name); var type = new TypeReference (@namespace, name, module, scope); MetadataSystem.TryProcessPrimitiveTypeReference (type); AdjustGenericParameters (type); var nested_names = type_info.nested_names; if (nested_names.IsNullOrEmpty ()) return type; for (int i = 0; i < nested_names.Length; i++) { type = new TypeReference (string.Empty, nested_names [i], module, null) { DeclaringType = type, }; AdjustGenericParameters (type); } return type; } static void AdjustGenericParameters (TypeReference type) { int arity; if (!TryGetArity (type.Name, out arity)) return; for (int i = 0; i < arity; i++) type.GenericParameters.Add (new GenericParameter (type)); } static IMetadataScope GetMetadataScope (ModuleDefinition module, Type type_info) { if (string.IsNullOrEmpty (type_info.assembly)) return module.TypeSystem.CoreLibrary; AssemblyNameReference match; var reference = AssemblyNameReference.Parse (type_info.assembly); return module.TryGetAssemblyNameReference (reference, out match) ? match : reference; } static bool TryGetDefinition (ModuleDefinition module, Type type_info, out TypeReference type) { type = null; if (!TryCurrentModule (module, type_info)) return false; var typedef = module.GetType (type_info.type_fullname); if (typedef == null) return false; var nested_names = type_info.nested_names; if (!nested_names.IsNullOrEmpty ()) { for (int i = 0; i < nested_names.Length; i++) { var nested_type = typedef.GetNestedType (nested_names [i]); if (nested_type == null) return false; typedef = nested_type; } } type = typedef; return true; } static bool TryCurrentModule (ModuleDefinition module, Type type_info) { if (string.IsNullOrEmpty (type_info.assembly)) return true; if (module.assembly != null && module.assembly.Name.FullName == type_info.assembly) return true; return false; } public static string ToParseable (TypeReference type, bool top_level = true) { if (type == null) return null; var name = new StringBuilder (); AppendType (type, name, true, top_level); return name.ToString (); } static void AppendNamePart (string part, StringBuilder name) { foreach (var c in part) { if (IsDelimiter (c)) name.Append ('\\'); name.Append (c); } } static void AppendType (TypeReference type, StringBuilder name, bool fq_name, bool top_level) { var element_type = type.GetElementType (); var declaring_type = element_type.DeclaringType; if (declaring_type != null) { AppendType (declaring_type, name, false, top_level); name.Append ('+'); } var @namespace = type.Namespace; if (!string.IsNullOrEmpty (@namespace)) { AppendNamePart (@namespace, name); name.Append ('.'); } AppendNamePart (element_type.Name, name); if (!fq_name) return; if (type.IsTypeSpecification ()) AppendTypeSpecification ((TypeSpecification) type, name); if (RequiresFullyQualifiedName (type, top_level)) { name.Append (", "); name.Append (GetScopeFullName (type)); } } static string GetScopeFullName (TypeReference type) { var scope = type.Scope; switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: return ((AssemblyNameReference) scope).FullName; case MetadataScopeType.ModuleDefinition: return ((ModuleDefinition) scope).Assembly.Name.FullName; } throw new ArgumentException (); } static void AppendTypeSpecification (TypeSpecification type, StringBuilder name) { if (type.ElementType.IsTypeSpecification ()) AppendTypeSpecification ((TypeSpecification) type.ElementType, name); switch (type.etype) { case ElementType.Ptr: name.Append ('*'); break; case ElementType.ByRef: name.Append ('&'); break; case ElementType.SzArray: case ElementType.Array: var array = (ArrayType) type; if (array.IsVector) { name.Append ("[]"); } else { name.Append ('['); for (int i = 1; i < array.Rank; i++) name.Append (','); name.Append (']'); } break; case ElementType.GenericInst: var instance = (GenericInstanceType) type; var arguments = instance.GenericArguments; name.Append ('['); for (int i = 0; i < arguments.Count; i++) { if (i > 0) name.Append (','); var argument = arguments [i]; var requires_fqname = argument.Scope != argument.Module; if (requires_fqname) name.Append ('['); AppendType (argument, name, true, false); if (requires_fqname) name.Append (']'); } name.Append (']'); break; default: return; } } static bool RequiresFullyQualifiedName (TypeReference type, bool top_level) { if (type.Scope == type.Module) return false; if (type.Scope.Name == "mscorlib" && top_level) return false; return true; } } }
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Lucene.Net.Support { /// <summary> /// Support class used to handle Hashtable addition, which does a check /// first to make sure the added item is unique in the hash. /// </summary> public class CollectionsHelper { public static void Add(System.Collections.Hashtable hashtable, System.Object item) { hashtable.Add(item, item); } public static void AddIfNotContains(System.Collections.Hashtable hashtable, System.Object item) { // Added lock around check. Even though the collection should already have // a synchronized wrapper around it, it doesn't prevent this test from having // race conditions. Two threads can (and have in TestIndexReaderReopen) call // hashtable.Contains(item) == false at the same time, then both try to add to // the hashtable, causing an ArgumentException. locking on the collection // prevents this. -- cc lock (hashtable) { if (hashtable.Contains(item) == false) { hashtable.Add(item, item); } } } public static void AddIfNotContains(System.Collections.ArrayList hashtable, System.Object item) { // see AddIfNotContains(Hashtable, object) for information about the lock lock (hashtable) { if (hashtable.Contains(item) == false) { hashtable.Add(item); } } } public static void AddAll<T>(ISet<T> set, IEnumerable<T> itemsToAdd) { foreach (var item in itemsToAdd) { set.Add(item); } } public static void AddAll(System.Collections.Hashtable hashtable, System.Collections.ICollection items) { System.Collections.IEnumerator iter = items.GetEnumerator(); System.Object item; while (iter.MoveNext()) { item = iter.Current; hashtable.Add(item, item); } } public static void AddAllIfNotContains(System.Collections.Hashtable hashtable, System.Collections.IList items) { System.Object item; for (int i = 0; i < items.Count; i++) { item = items[i]; if (hashtable.Contains(item) == false) { hashtable.Add(item, item); } } } public static void AddAllIfNotContains(System.Collections.Hashtable hashtable, System.Collections.ICollection items) { System.Collections.IEnumerator iter = items.GetEnumerator(); System.Object item; while (iter.MoveNext()) { item = iter.Current; if (hashtable.Contains(item) == false) { hashtable.Add(item, item); } } } public static void AddAllIfNotContains(System.Collections.Generic.IDictionary<string, string> hashtable, System.Collections.Generic.ICollection<string> items) { foreach (string s in items) { if (hashtable.ContainsKey(s) == false) { hashtable.Add(s, s); } } } public static void AddAll(System.Collections.Generic.IDictionary<string, string> hashtable, System.Collections.Generic.ICollection<string> items) { foreach (string s in items) { hashtable.Add(s, s); } } public static System.String CollectionToString(System.Collections.Generic.IDictionary<string, string> c) { Hashtable t = new Hashtable(); foreach (string key in c.Keys) { t.Add(key, c[key]); } return CollectionToString(t); } /// <summary> /// Converts the specified collection to its string representation. /// </summary> /// <param name="c">The collection to convert to string.</param> /// <returns>A string representation of the specified collection.</returns> public static System.String CollectionToString(System.Collections.ICollection c) { System.Text.StringBuilder s = new System.Text.StringBuilder(); if (c != null) { System.Collections.ArrayList l = new System.Collections.ArrayList(c); bool isDictionary = (c is System.Collections.BitArray || c is System.Collections.Hashtable || c is System.Collections.IDictionary || c is System.Collections.Specialized.NameValueCollection || (l.Count > 0 && l[0] is System.Collections.DictionaryEntry)); for (int index = 0; index < l.Count; index++) { if (l[index] == null) s.Append("null"); else if (!isDictionary) s.Append(l[index]); else { isDictionary = true; if (c is System.Collections.Specialized.NameValueCollection) s.Append(((System.Collections.Specialized.NameValueCollection)c).GetKey(index)); else s.Append(((System.Collections.DictionaryEntry)l[index]).Key); s.Append("="); if (c is System.Collections.Specialized.NameValueCollection) s.Append(((System.Collections.Specialized.NameValueCollection)c).GetValues(index)[0]); else s.Append(((System.Collections.DictionaryEntry)l[index]).Value); } if (index < l.Count - 1) s.Append(", "); } if (isDictionary) { if (c is System.Collections.ArrayList) isDictionary = false; } if (isDictionary) { s.Insert(0, "{"); s.Append("}"); } else { s.Insert(0, "["); s.Append("]"); } } else s.Insert(0, "null"); return s.ToString(); } /// <summary> /// Compares two string arrays for equality. /// </summary> /// <param name="l1">First string array list to compare</param> /// <param name="l2">Second string array list to compare</param> /// <returns>true if the strings are equal in both arrays, false otherwise</returns> public static bool CompareStringArrays(System.String[] l1, System.String[] l2) { if (l1.Length != l2.Length) return false; for (int i = 0; i < l1.Length; i++) { if (l1[i] != l2[i]) return false; } return true; } /// <summary> /// Fills the array with an specific value from an specific index to an specific index. /// </summary> /// <param name="array">The array to be filled.</param> /// <param name="fromindex">The first index to be filled.</param> /// <param name="toindex">The last index to be filled.</param> /// <param name="val">The value to fill the array with.</param> public static void Fill(System.Array array, System.Int32 fromindex, System.Int32 toindex, System.Object val) { System.Object Temp_Object = val; System.Type elementtype = array.GetType().GetElementType(); if (elementtype != val.GetType()) Temp_Object = Convert.ChangeType(val, elementtype); if (array.Length == 0) throw (new System.NullReferenceException()); if (fromindex > toindex) throw (new System.ArgumentException()); if ((fromindex < 0) || ((System.Array)array).Length < toindex) throw (new System.IndexOutOfRangeException()); for (int index = (fromindex > 0) ? fromindex-- : fromindex; index < toindex; index++) array.SetValue(Temp_Object, index); } /// <summary> /// Fills the array with an specific value. /// </summary> /// <param name="array">The array to be filled.</param> /// <param name="val">The value to fill the array with.</param> public static void Fill(System.Array array, System.Object val) { Fill(array, 0, array.Length, val); } /// <summary> /// Compares the entire members of one array whith the other one. /// </summary> /// <param name="array1">The array to be compared.</param> /// <param name="array2">The array to be compared with.</param> /// <returns>Returns true if the two specified arrays of Objects are equal /// to one another. The two arrays are considered equal if both arrays /// contain the same number of elements, and all corresponding pairs of /// elements in the two arrays are equal. Two objects e1 and e2 are /// considered equal if (e1==null ? e2==null : e1.equals(e2)). In other /// words, the two arrays are equal if they contain the same elements in /// the same order. Also, two array references are considered equal if /// both are null.</returns> public static bool Equals(System.Array array1, System.Array array2) { bool result = false; if ((array1 == null) && (array2 == null)) result = true; else if ((array1 != null) && (array2 != null)) { if (array1.Length == array2.Length) { int length = array1.Length; result = true; for (int index = 0; index < length; index++) { System.Object o1 = array1.GetValue(index); System.Object o2 = array2.GetValue(index); if (o1 == null && o2 == null) continue; // they match else if (o1 == null || !o1.Equals(o2)) { result = false; break; } } } } return result; } public static bool DictEquals<TKey>(IDictionary<TKey, object> first, IDictionary<TKey, object> second) { if (first == second) return true; if ((first == null) || (second == null)) return false; if (first.Count != second.Count) return false; var comparer = EqualityComparer<object>.Default; foreach (var kvp in first) { object secondValue; if (!second.TryGetValue(kvp.Key, out secondValue)) return false; if (!comparer.Equals(kvp.Value, secondValue)) return false; } return true; } public static void Swap<T>(IList<T> list, int index1, int index2) { T tmp = list[index1]; list[index1] = list[index2]; list[index2] = tmp; } // Method found here http://www.dailycoding.com/Posts/random_sort_a_list_using_linq.aspx public static IList<T> Shuffle<T>(IList<T> list) { return list.OrderBy(str => Guid.NewGuid()).ToList(); } public static KeyValuePair<int, TValue> LowerEntry<TValue>(SortedDictionary<int, TValue> sd, int keyLimit) { KeyValuePair<int, TValue> retKVPair = default(KeyValuePair<int, TValue>); foreach (var kvPair in sd) { if (kvPair.Key < keyLimit) { retKVPair = kvPair; } else { // No other key lesser key found break; } } return retKVPair; } public static IDictionary<TKey, TValue> EmptyMap<TKey, TValue>() { // todo: should this return a singleton instance? return new HashMap<TKey, TValue>(); } public static IDictionary<TKey, TValue> UnmodifiableMap<TKey, TValue>(IDictionary<TKey, TValue> dict) { return new UnmodifiableDictionary<TKey, TValue>(dict); } public static IDictionary<TKey, TValue> SingletonMap<TKey, TValue>(TKey key, TValue value) { return new Dictionary<TKey, TValue>() { {key, value} }; } public class ReverseComparer<T> : IComparer<T> { public int Compare(T x, T y) { return (new CaseInsensitiveComparer()).Compare(y, x); } } } }
// 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.Diagnostics; using System.Globalization; using Microsoft.CSharp.RuntimeBinder.Semantics; namespace Microsoft.CSharp.RuntimeBinder.Errors { // Collection of error reporting code. This class contains among other things ptrs to // interfaces for constructing error locations (EE doesn't need locations), submitting errors // (EE and compiler have different destinations), and error construction (again EE and // compiler differ). Further decoupling would be enabled if the construction of substitution // strings (the values that replace the placeholders in resource-defined error strings) were // done at the location in which the error is detected. Right now an ErrArg is constructed // and later is used to construct a string. I can't see any reason why the string creation // must be deferred, thus causing the error formatting/reporting subsystem to understand a // whole host of types, many of which may not be relevant to the EE. internal sealed class ErrorHandling { private readonly IErrorSink _errorSink; private readonly UserStringBuilder _userStringBuilder; private readonly CErrorFactory _errorFactory; // By default these DO NOT add related locations. To add a related location, pass an ErrArgRef. public void Error(ErrorCode id, params ErrArg[] args) { ErrorTreeArgs(id, args); } // By default these DO add related locations. public void ErrorRef(ErrorCode id, params ErrArgRef[] args) { ErrorTreeArgs(id, args); } //////////////////////////////////////////////////////////////////////////////// // // This function submits the given error to the controller, and if it's a fatal // error, throws the fatal exception. public void SubmitError(CParameterizedError error) { _errorSink?.SubmitError(error); } private void MakeErrorLocArgs(out CParameterizedError error, ErrorCode id, ErrArg[] prgarg) { error = new CParameterizedError(); error.Initialize(id, prgarg); } public void AddRelatedSymLoc(CParameterizedError err, Symbol sym) { } public void AddRelatedTypeLoc(CParameterizedError err, CType pType) { } private void MakeErrorTreeArgs(out CParameterizedError error, ErrorCode id, ErrArg[] prgarg) { MakeErrorLocArgs(out error, id, prgarg); } // By default these DO NOT add related locations. To add a related location, pass an ErrArgRef. public void MakeError(out CParameterizedError error, ErrorCode id, params ErrArg[] args) { MakeErrorTreeArgs(out error, id, args); } public ErrorHandling( UserStringBuilder strBldr, IErrorSink sink, CErrorFactory factory) { Debug.Assert(factory != null); _userStringBuilder = strBldr; _errorSink = sink; _errorFactory = factory; } private CError CreateError(ErrorCode iErrorIndex, string[] args) { return _errorFactory.CreateError(iErrorIndex, args); } private void ErrorTreeArgs(ErrorCode id, ErrArg[] prgarg) { CParameterizedError error; MakeErrorTreeArgs(out error, id, prgarg); SubmitError(error); } public CError RealizeError(CParameterizedError parameterizedError) { // Create an arg array manually using the type information in the ErrArgs. string[] prgpsz = new string[parameterizedError.GetParameterCount()]; int[] prgiarg = new int[parameterizedError.GetParameterCount()]; int ppsz = 0; int piarg = 0; int cargUnique = 0; for (int iarg = 0; iarg < parameterizedError.GetParameterCount(); iarg++) { ErrArg arg = parameterizedError.GetParameter(iarg); // If the NoStr bit is set we don't add it to prgpsz. if (0 != (arg.eaf & ErrArgFlags.NoStr)) continue; bool fUserStrings = false; if (!_userStringBuilder.ErrArgToString(out prgpsz[ppsz], arg, out fUserStrings)) { if (arg.eak == ErrArgKind.Int) { prgpsz[ppsz] = arg.n.ToString(CultureInfo.InvariantCulture); } } ppsz++; int iargRec; if (!fUserStrings || 0 == (arg.eaf & ErrArgFlags.Unique)) { iargRec = -1; } else { iargRec = iarg; cargUnique++; } prgiarg[piarg] = iargRec; piarg++; } int cpsz = ppsz; if (cargUnique > 1) { // Copy the strings over to another buffer. string[] prgpszNew = new string[cpsz]; Array.Copy(prgpsz, 0, prgpszNew, 0, cpsz); for (int i = 0; i < cpsz; i++) { if (prgiarg[i] < 0 || prgpszNew[i] != prgpsz[i]) continue; ErrArg arg = parameterizedError.GetParameter(prgiarg[i]); Debug.Assert(0 != (arg.eaf & ErrArgFlags.Unique) && 0 == (arg.eaf & ErrArgFlags.NoStr)); Symbol sym = null; CType pType = null; switch (arg.eak) { case ErrArgKind.Sym: sym = arg.sym; break; case ErrArgKind.Type: pType = arg.pType; break; case ErrArgKind.SymWithType: sym = arg.swtMemo.sym; break; case ErrArgKind.MethWithInst: sym = arg.mpwiMemo.sym; break; default: Debug.Assert(false, "Shouldn't be here!"); continue; } bool fMunge = false; for (int j = i + 1; j < cpsz; j++) { if (prgiarg[j] < 0) continue; Debug.Assert(0 != (parameterizedError.GetParameter(prgiarg[j]).eaf & ErrArgFlags.Unique)); if (prgpsz[i] != prgpsz[j]) continue; // The strings are identical. If they are the same symbol, leave them alone. // Otherwise, munge both strings. If j has already been munged, just make // sure we munge i. if (prgpszNew[j] != prgpsz[j]) { fMunge = true; continue; } ErrArg arg2 = parameterizedError.GetParameter(prgiarg[j]); Debug.Assert(0 != (arg2.eaf & ErrArgFlags.Unique) && 0 == (arg2.eaf & ErrArgFlags.NoStr)); Symbol sym2 = null; CType pType2 = null; switch (arg2.eak) { case ErrArgKind.Sym: sym2 = arg2.sym; break; case ErrArgKind.Type: pType2 = arg2.pType; break; case ErrArgKind.SymWithType: sym2 = arg2.swtMemo.sym; break; case ErrArgKind.MethWithInst: sym2 = arg2.mpwiMemo.sym; break; default: Debug.Assert(false, "Shouldn't be here!"); continue; } if (sym2 == sym && pType2 == pType && !fMunge) continue; prgpszNew[j] = prgpsz[j]; fMunge = true; } if (fMunge) { prgpszNew[i] = prgpsz[i]; } } prgpsz = prgpszNew; } CError err = CreateError(parameterizedError.GetErrorNumber(), prgpsz); return err; } } }
/* * Copyright (C) 2012, 2013 OUYA, 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 UnityEngine; using Object=UnityEngine.Object; using Random = UnityEngine.Random; public class OuyaShowGuitar : MonoBehaviour, OuyaSDK.IPauseListener, OuyaSDK.IResumeListener, OuyaSDK.IMenuButtonUpListener, OuyaSDK.IMenuAppearingListener { [Serializable] public class CubeLaneItem { public GameObject StartPosition = null; public GameObject EndPosition = null; public Color LaneColor = Color.green; public OuyaSDK.KeyEnum LaneButton = OuyaSDK.KeyEnum.HARMONIX_ROCK_BAND_GUITAR_GREEN; public GameObject Instance = null; public AudioSource LaneSound = null; } public List<CubeLaneItem> Lanes = new List<CubeLaneItem>(); [Serializable] public class NoteItem { public CubeLaneItem Parent = null; public GameObject Instance = null; public DateTime StartTime = DateTime.MinValue; public DateTime EndTime = DateTime.MinValue; public DateTime FadeTime = DateTime.MinValue; public bool UseLower = false; } private List<NoteItem> Notes = new List<NoteItem>(); private int NoteTimeToLive = 4000; private int NoteTimeToCreate = 100; private int NoteTimeToFade = 250; private Dictionary<OuyaSDK.KeyEnum, bool> LastPressed = new Dictionary<OuyaSDK.KeyEnum, bool>(); private DateTime m_timerCreate = DateTime.MinValue; private float LastStrum = 0f; public Transform TrackEnd = null; void Awake() { OuyaSDK.registerMenuButtonUpListener(this); OuyaSDK.registerMenuAppearingListener(this); OuyaSDK.registerPauseListener(this); OuyaSDK.registerResumeListener(this); } void OnDestroy() { OuyaSDK.unregisterMenuButtonUpListener(this); OuyaSDK.unregisterMenuAppearingListener(this); OuyaSDK.unregisterPauseListener(this); OuyaSDK.unregisterResumeListener(this); DestroyNotes(); } public void OuyaMenuButtonUp() { Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString()); } public void OuyaMenuAppearing() { Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString()); } public void OuyaOnPause() { Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString()); } public void OuyaOnResume() { Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString()); } public void DestroyNote(NoteItem note) { if (note.Instance) { Object.DestroyImmediate(note.Instance, true); note.Instance = null; } } public void DestroyNotes() { foreach (NoteItem note in Notes) { DestroyNote(note); } Notes.Clear(); } public void CreateNote(CubeLaneItem item) { NoteItem note = new NoteItem(); note.StartTime = DateTime.Now; note.EndTime = DateTime.Now + TimeSpan.FromMilliseconds(NoteTimeToLive); note.Parent = item; note.Instance = (GameObject)Instantiate(item.StartPosition); (note.Instance.renderer as MeshRenderer).material.color = item.LaneColor; if (0 == Random.Range(0, 10)) { note.UseLower = true; note.Instance.transform.rotation = Quaternion.Euler(0, 15, 0); } Notes.Add(note); } void Update() { if (m_timerCreate < DateTime.Now) { m_timerCreate = DateTime.Now + TimeSpan.FromMilliseconds(NoteTimeToCreate); int index = Random.Range(0, Lanes.Count); CreateNote(Lanes[index]); } bool lower = OuyaExampleCommon.GetButton(OuyaSDK.KeyEnum.HARMONIX_ROCK_BAND_GUITAR_LOWER, OuyaSDK.OuyaPlayer.player1); float strum = OuyaExampleCommon.GetAxis(OuyaSDK.KeyEnum.HARMONIX_ROCK_BAND_GUITAR_STRUM, OuyaSDK.OuyaPlayer.player1); bool strumChanged = LastStrum != strum; LastStrum = strum; foreach (CubeLaneItem item in Lanes) { // cache the button state LastPressed[item.LaneButton] = OuyaExampleCommon.GetButton(item.LaneButton, OuyaSDK.OuyaPlayer.player1); } List<NoteItem> removeList = new List<NoteItem>(); foreach (NoteItem note in Notes) { if (note.EndTime < DateTime.Now) { removeList.Add(note); continue; } float elapsed = (float)(DateTime.Now - note.StartTime).TotalMilliseconds; note.Instance.transform.position = Vector3.Lerp( note.Parent.StartPosition.transform.position, note.Parent.EndPosition.transform.position, elapsed/(float) NoteTimeToLive); bool inRange = Mathf.Abs(TrackEnd.position.z - note.Instance.transform.position.z) <= 16; bool afterRange = (note.Instance.transform.position.z - 8) < TrackEnd.position.z; if (inRange) { (note.Instance.renderer as MeshRenderer).material.color = Color.white; } else if (afterRange) { (note.Instance.renderer as MeshRenderer).material.color = new Color(0, 0, 0, 0.75f); } // use available press of the lane button if (LastPressed.ContainsKey(note.Parent.LaneButton) && LastPressed[note.Parent.LaneButton]) { if ( //check if note is across the finish line inRange && //check if lower was used (!note.UseLower || lower == note.UseLower) && // check if strum was used strumChanged && strum != 0f) { //use button press LastPressed[note.Parent.LaneButton] = false; //hit the note if (note.FadeTime == DateTime.MinValue) { note.FadeTime = DateTime.Now + TimeSpan.FromMilliseconds(NoteTimeToFade); note.Parent.LaneSound.volume = 1; } } } if (note.FadeTime != DateTime.MinValue) { if (note.FadeTime < DateTime.Now) { removeList.Add(note); continue; } elapsed = (float)(note.FadeTime - DateTime.Now).TotalMilliseconds; (note.Instance.renderer as MeshRenderer).material.color = Color.Lerp(note.Parent.LaneColor, Color.clear, 1f - elapsed / (float)NoteTimeToFade); note.Instance.transform.localScale = Vector3.Lerp(note.Instance.transform.localScale, note.Parent.StartPosition.transform.localScale * 2, elapsed / (float)NoteTimeToFade); } } foreach (NoteItem note in removeList) { Notes.Remove(note); DestroyNote(note); } } void FixedUpdate() { foreach (CubeLaneItem item in Lanes) { item.LaneSound.volume = Mathf.Lerp(item.LaneSound.volume, 0, Time.fixedDeltaTime); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using System.Runtime.CompilerServices; using System.Text; namespace System.Numerics { /// <summary> /// A structure encapsulating three single precision floating point values and provides hardware accelerated methods. /// </summary> public partial struct Vector3 : IEquatable<Vector3>, IFormattable { #region Public Static Properties /// <summary> /// Returns the vector (0,0,0). /// </summary> public static Vector3 Zero { get { return new Vector3(); } } /// <summary> /// Returns the vector (1,1,1). /// </summary> public static Vector3 One { get { return new Vector3(1.0f, 1.0f, 1.0f); } } /// <summary> /// Returns the vector (1,0,0). /// </summary> public static Vector3 UnitX { get { return new Vector3(1.0f, 0.0f, 0.0f); } } /// <summary> /// Returns the vector (0,1,0). /// </summary> public static Vector3 UnitY { get { return new Vector3(0.0f, 1.0f, 0.0f); } } /// <summary> /// Returns the vector (0,0,1). /// </summary> public static Vector3 UnitZ { get { return new Vector3(0.0f, 0.0f, 1.0f); } } #endregion Public Static Properties #region Public Instance Methods /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int hash = this.X.GetHashCode(); hash = HashCodeHelper.CombineHashCodes(hash, this.Y.GetHashCode()); hash = HashCodeHelper.CombineHashCodes(hash, this.Z.GetHashCode()); return hash; } /// <summary> /// Returns a boolean indicating whether the given Object is equal to this Vector3 instance. /// </summary> /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this Vector3; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (!(obj is Vector3)) return false; return Equals((Vector3)obj); } /// <summary> /// Returns a String representing this Vector3 instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() { return ToString("G", CultureInfo.CurrentCulture); } /// <summary> /// Returns a String representing this Vector3 instance, using the specified format to format individual elements. /// </summary> /// <param name="format">The format of individual elements.</param> /// <returns>The string representation.</returns> public string ToString(string format) { return ToString(format, CultureInfo.CurrentCulture); } /// <summary> /// Returns a String representing this Vector3 instance, using the specified format to format individual elements /// and the given IFormatProvider. /// </summary> /// <param name="format">The format of individual elements.</param> /// <param name="formatProvider">The format provider to use when formatting elements.</param> /// <returns>The string representation.</returns> public string ToString(string format, IFormatProvider formatProvider) { StringBuilder sb = new StringBuilder(); string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator + " "; sb.Append("<"); sb.Append(((IFormattable)this.X).ToString(format, formatProvider)); sb.Append(separator); sb.Append(((IFormattable)this.Y).ToString(format, formatProvider)); sb.Append(separator); sb.Append(((IFormattable)this.Z).ToString(format, formatProvider)); sb.Append(">"); return sb.ToString(); } /// <summary> /// Returns the length of the vector. /// </summary> /// <returns>The vector's length.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public float Length() { if (Vector.IsHardwareAccelerated) { float ls = Vector3.Dot(this, this); return (float)System.Math.Sqrt(ls); } else { float ls = X * X + Y * Y + Z * Z; return (float)System.Math.Sqrt(ls); } } /// <summary> /// Returns the length of the vector squared. This operation is cheaper than Length(). /// </summary> /// <returns>The vector's length squared.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public float LengthSquared() { if (Vector.IsHardwareAccelerated) { return Vector3.Dot(this, this); } else { return X * X + Y * Y + Z * Z; } } #endregion Public Instance Methods #region Public Static Methods /// <summary> /// Returns the Euclidean distance between the two given points. /// </summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector3 value1, Vector3 value2) { if (Vector.IsHardwareAccelerated) { Vector3 difference = value1 - value2; float ls = Vector3.Dot(difference, difference); return (float)System.Math.Sqrt(ls); } else { float dx = value1.X - value2.X; float dy = value1.Y - value2.Y; float dz = value1.Z - value2.Z; float ls = dx * dx + dy * dy + dz * dz; return (float)System.Math.Sqrt((double)ls); } } /// <summary> /// Returns the Euclidean distance squared between the two given points. /// </summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance squared.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DistanceSquared(Vector3 value1, Vector3 value2) { if (Vector.IsHardwareAccelerated) { Vector3 difference = value1 - value2; return Vector3.Dot(difference, difference); } else { float dx = value1.X - value2.X; float dy = value1.Y - value2.Y; float dz = value1.Z - value2.Z; return dx * dx + dy * dy + dz * dz; } } /// <summary> /// Returns a vector with the same direction as the given vector, but with a length of 1. /// </summary> /// <param name="value">The vector to normalize.</param> /// <returns>The normalized vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Normalize(Vector3 value) { if (Vector.IsHardwareAccelerated) { float length = value.Length(); return value / length; } else { float ls = value.X * value.X + value.Y * value.Y + value.Z * value.Z; float length = (float)System.Math.Sqrt(ls); return new Vector3(value.X / length, value.Y / length, value.Z / length); } } /// <summary> /// Computes the cross product of two vectors. /// </summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <returns>The cross product.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Cross(Vector3 vector1, Vector3 vector2) { return new Vector3( vector1.Y * vector2.Z - vector1.Z * vector2.Y, vector1.Z * vector2.X - vector1.X * vector2.Z, vector1.X * vector2.Y - vector1.Y * vector2.X); } /// <summary> /// Returns the reflection of a vector off a surface that has the specified normal. /// </summary> /// <param name="vector">The source vector.</param> /// <param name="normal">The normal of the surface being reflected off.</param> /// <returns>The reflected vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Reflect(Vector3 vector, Vector3 normal) { if (Vector.IsHardwareAccelerated) { float dot = Vector3.Dot(vector, normal); Vector3 temp = normal * dot * 2f; return vector - temp; } else { float dot = vector.X * normal.X + vector.Y * normal.Y + vector.Z * normal.Z; float tempX = normal.X * dot * 2f; float tempY = normal.Y * dot * 2f; float tempZ = normal.Z * dot * 2f; return new Vector3(vector.X - tempX, vector.Y - tempY, vector.Z - tempZ); } } /// <summary> /// Restricts a vector between a min and max value. /// </summary> /// <param name="value1">The source vector.</param> /// <param name="min">The minimum value.</param> /// <param name="max">The maximum value.</param> /// <returns>The restricted vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max) { // This compare order is very important!!! // We must follow HLSL behavior in the case user specified min value is bigger than max value. float x = value1.X; x = (x > max.X) ? max.X : x; x = (x < min.X) ? min.X : x; float y = value1.Y; y = (y > max.Y) ? max.Y : y; y = (y < min.Y) ? min.Y : y; float z = value1.Z; z = (z > max.Z) ? max.Z : z; z = (z < min.Z) ? min.Z : z; return new Vector3(x, y, z); } /// <summary> /// Linearly interpolates between two vectors based on the given weighting. /// </summary> /// <param name="value1">The first source vector.</param> /// <param name="value2">The second source vector.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of the second source vector.</param> /// <returns>The interpolated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount) { if (Vector.IsHardwareAccelerated) { Vector3 firstInfluence = value1 * (1f - amount); Vector3 secondInfluence = value2 * amount; return firstInfluence + secondInfluence; } else { return new Vector3( value1.X + (value2.X - value1.X) * amount, value1.Y + (value2.Y - value1.Y) * amount, value1.Z + (value2.Z - value1.Z) * amount); } } /// <summary> /// Transforms a vector by the given matrix. /// </summary> /// <param name="position">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Transform(Vector3 position, Matrix4x4 matrix) { return new Vector3( position.X * matrix.M11 + position.Y * matrix.M21 + position.Z * matrix.M31 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + position.Z * matrix.M32 + matrix.M42, position.X * matrix.M13 + position.Y * matrix.M23 + position.Z * matrix.M33 + matrix.M43); } /// <summary> /// Transforms a vector normal by the given matrix. /// </summary> /// <param name="normal">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 TransformNormal(Vector3 normal, Matrix4x4 matrix) { return new Vector3( normal.X * matrix.M11 + normal.Y * matrix.M21 + normal.Z * matrix.M31, normal.X * matrix.M12 + normal.Y * matrix.M22 + normal.Z * matrix.M32, normal.X * matrix.M13 + normal.Y * matrix.M23 + normal.Z * matrix.M33); } /// <summary> /// Transforms a vector by the given Quaternion rotation value. /// </summary> /// <param name="value">The source vector to be rotated.</param> /// <param name="rotation">The rotation to apply.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Transform(Vector3 value, Quaternion rotation) { float x2 = rotation.X + rotation.X; float y2 = rotation.Y + rotation.Y; float z2 = rotation.Z + rotation.Z; float wx2 = rotation.W * x2; float wy2 = rotation.W * y2; float wz2 = rotation.W * z2; float xx2 = rotation.X * x2; float xy2 = rotation.X * y2; float xz2 = rotation.X * z2; float yy2 = rotation.Y * y2; float yz2 = rotation.Y * z2; float zz2 = rotation.Z * z2; return new Vector3( value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2) + value.Z * (xz2 + wy2), value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2) + value.Z * (yz2 - wx2), value.X * (xz2 - wy2) + value.Y * (yz2 + wx2) + value.Z * (1.0f - xx2 - yy2)); } #endregion Public Static Methods #region Public operator methods // All these methods should be inlined as they are implemented // over JIT intrinsics /// <summary> /// Adds two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The summed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Add(Vector3 left, Vector3 right) { return left + right; } /// <summary> /// Subtracts the second vector from the first. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The difference vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Subtract(Vector3 left, Vector3 right) { return left - right; } /// <summary> /// Multiplies two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The product vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(Vector3 left, Vector3 right) { return left * right; } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The source vector.</param> /// <param name="right">The scalar value.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(Vector3 left, Single right) { return left * right; } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The scalar value.</param> /// <param name="right">The source vector.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(Single left, Vector3 right) { return left * right; } /// <summary> /// Divides the first vector by the second. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The vector resulting from the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Divide(Vector3 left, Vector3 right) { return left / right; } /// <summary> /// Divides the vector by the given scalar. /// </summary> /// <param name="left">The source vector.</param> /// <param name="divisor">The scalar value.</param> /// <returns>The result of the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Divide(Vector3 left, Single divisor) { return left / divisor; } /// <summary> /// Negates a given vector. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The negated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Negate(Vector3 value) { return -value; } #endregion Public operator methods } }
#region Using Directives using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Figlut.MonoDroid.Toolkit.Utilities.SettingsFile; using Figlut.MonoDroid.Toolkit.Utilities; using Figlut.MonoDroid.Toolkit.Utilities.Serialization; using Figlut.MonoDroid.Toolkit.Utilities.Logging; using Figlut.MonoDroid.Toolkit; #endregion //Using Directives namespace Figlut.MonoDroid.DataBox.Configuration { public class FiglutMonoDroidDataBoxSettings : Settings { #region Constructors public FiglutMonoDroidDataBoxSettings() { } public FiglutMonoDroidDataBoxSettings(string filePath) : base(filePath) { } public FiglutMonoDroidDataBoxSettings(string name, string filePath) : base(name, filePath) { } #endregion //Constructors #region Fields #region Web Service private string _figlutWebServiceBaseUrl; private bool _useAuthentication; private bool _promptForCredentials; private string _authenticationDomainName; private string _authenticationUserName; private string _authenticationPassword; private int _figlutWebServiceWebRequestTimeout; private TextEncodingType _figlutWebServiceTextResponseEncoding; private SerializerType _figlutWebServiceMessagingFormat; private SerializerType _figlutWebServiceSchemaAcquisitionMessagingFormat; private bool _offlineMode; #endregion //Web Service #region DataBox private string _applicationTitle; private string _applicationVersion; private ColorName _themeColor; private string _applicationBannerImageFileName; private bool _shapeColumnNames; private int _primaryColumnIndex; private int _secondaryColumnIndex; private List<string> _hiddenTypeNames; private List<Type> _hiddenTypes; private string _entityIdColumnName; private bool _hideEntityIdColumn; private bool _treatZeroAsNull; private bool _closeAddWindowAfterAdd; private string _databaseSchemaFileName; private bool _useExtensions; private string _extensionAssemblyName; private string _crudInterceptorFullTypeName; private string _mainMenuExtensionFullTypeName; #endregion //DataBox #region Logging private bool _logToFile; private string _logFileName; private LoggingLevel _loggingLevel; #endregion //Logging #endregion //Fields #region Properties #region Web Service [SettingInfo("Web Service", DisplayName = "Base URL", Description = "The URL of the Figlut Web Service.", CategorySequenceId = 0)] public string FiglutWebServiceBaseUrl { get { return _figlutWebServiceBaseUrl; } set { _figlutWebServiceBaseUrl = value; } } [SettingInfo("Web Service", AutoFormatDisplayName = true, Description = "Whether or not tht Figlut Web Service requires clients to authenticate.", CategorySequenceId = 1)] public bool UseAuthentication { get { return _useAuthentication; } set { _useAuthentication = value; } } [SettingInfo("Web Service", AutoFormatDisplayName = true, Description = "Whether or not to prompt for credentials on application start up or otherwise use the credentials specified in these settings.", CategorySequenceId = 2)] public bool PromptForCredentials { get { return _promptForCredentials; } set { _promptForCredentials = value; } } [SettingInfo("Web Service", DisplayName = "Domain Name", Description = "The domain name (or hostname) to be used in the credentials when authenticating against the Figlut Web Service.", CategorySequenceId = 3)] public string AuthenticationDomainName { get { return _authenticationDomainName; } set { _authenticationDomainName = value; } } [SettingInfo("Web Service", DisplayName = "User Name", Description = "The windows user name to be used in the credentials when authenticating against the Figlut Web Service. N.B. Only used if the user is not prompted for credentials.", CategorySequenceId = 4)] public string AuthenticationUserName { get { return _authenticationUserName; } set { _authenticationUserName = value; } } [SettingInfo("Web Service", DisplayName = "Password", Description = "The password of the windows user to be used in the credentials when authentication against the Figlut Web Service.", CategorySequenceId = 5, PasswordChar = '*')] public string AuthenticationPassword { get { return _authenticationPassword; } set { _authenticationPassword = value; } } [SettingInfo("Web Service", DisplayName = "Web Request Timeout", Description = "The timeout in milliseconds of a web request made to the Figlut Web Service by the DataBox.", CategorySequenceId = 6)] public int FiglutWebServiceWebRequestTimeout { get { return _figlutWebServiceWebRequestTimeout; } set { _figlutWebServiceWebRequestTimeout = value; } } [SettingInfo("Web Service", DisplayName = "Text Response Encoding", Description = "The encoding of the text response from Figlut Web Service. The encoding of the Figlut DataBox and Web Service need to be configured to match.", CategorySequenceId = 7)] public TextEncodingType FiglutWebServiceTextResponseEncoding { get { return _figlutWebServiceTextResponseEncoding; } set { _figlutWebServiceTextResponseEncoding = value; } } [SettingInfo("Web Service", DisplayName = "Messaging Format", Description = "The format of the messages exchanged between the Figlut DataBox and the Web Service e.g. XML, JSON or CSV.", Visible = false, CategorySequenceId = 8)] public SerializerType FiglutWebServiceMessagingFormat { get { return _figlutWebServiceMessagingFormat; } set { _figlutWebServiceMessagingFormat = value; } } [SettingInfo("Web Service", DisplayName = "Schema Acquisition Messaging Format", Description = "The format of the messages exchanged between the Figlut DataBox and the Web Service when acquiring the database schema.", Visible = false, CategorySequenceId = 9)] public SerializerType FiglutWebServiceSchemaAcquisitionMessagingFormat { get { return _figlutWebServiceSchemaAcquisitionMessagingFormat; } set { _figlutWebServiceSchemaAcquisitionMessagingFormat = value; } } [SettingInfo("Web Service", AutoFormatDisplayName = true, Description = "Whether to download the database schema from the Figlut Web Service when DataBox starts up.", Visible = false, CategorySequenceId = 10)] public bool OfflineMode { get { return _offlineMode; } set { _offlineMode = value; } } #endregion //Web Service #region DataBox [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "The name of the application. Leaving this setting blank defaults the title.", CategorySequenceId = 0)] public string ApplicationTitle { get { return _applicationTitle; } set { _applicationTitle = value; } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "The version of the application. Leaving this setting blank defaults the version.", CategorySequenceId = 1)] public string ApplicationVersion { get { return _applicationVersion; } set { _applicationVersion = value; ;} } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "The theme color. Leaving this field blank defaults the color.", CategorySequenceId = 2)] public ColorName ThemeColor { get { return _themeColor; } set { _themeColor = value; } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "The image to be displayed in the application's banner.", SelectFilePath = true, CategorySequenceId = 3)] public string ApplicationBannerImageFilePath { get { return _applicationBannerImageFileName; } set { _applicationBannerImageFileName = value; ;} } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "Whether or not to rename the column names in the DataBox by adding spaces in between upper case letters for camel cased column names.", CategorySequenceId = 4)] public bool ShapeColumnNames { get { return _shapeColumnNames; } set { _shapeColumnNames = true; } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "The index of the main column value to display in the DataBox screen from where you select to see the details of a record.", CategorySequenceId = 5)] public int PrimaryColumnIndex { get{ return _primaryColumnIndex; } set{ _primaryColumnIndex = value; } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "The index of the secondary column value to display in the DataBox from where you select to see the details of the a record.", CategorySequenceId = 6)] public int SecondaryColumnIndex { get{ return _secondaryColumnIndex; } set{ _secondaryColumnIndex = value; } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "The types of entity properties to hide from view in the DataBox.", CategorySequenceId = 7)] public List<string> HiddenTypeNames { get { return _hiddenTypeNames; } set { _hiddenTypeNames = value; RefreshHiddenTypes(); } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "The name of the dynamically created column used to uniquely identify and lookup rows in the DataBox. This setting should not be changed unless the target database contains a table with a column name matching this setting's value i.e. because column names need to be unique.", CategorySequenceId = 8)] public string EntityIdColumnName { get { return _entityIdColumnName; } set { _entityIdColumnName = value; } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "Whether or not to hide the dynamically created entity id column used to uniquely identify and look up rows in the DataBox. Under normal circumstances for presentation purposes this value should be set to 'true' i.e. in order to not display the entity ID.", CategorySequenceId = 9)] public bool HideEntityIdColumn { get { return _hideEntityIdColumn; } set { _hideEntityIdColumn = value; } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "Whether to treat zeros as null. N.B. Setting this value to tru will prevent user from entering zero into not nullable numeric fields.", CategorySequenceId = 10)] public bool TreatZeroAsNull { get { return _treatZeroAsNull; } set { _treatZeroAsNull = value; } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "Whether the add window should be closed after adding an entity.", CategorySequenceId = 11)] public bool CloseAddWindowAfterAdd { get { return _closeAddWindowAfterAdd; } set { _closeAddWindowAfterAdd = value; } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "The name of the file where the database schema info is saved to.", Visible = false, CategorySequenceId = 12)] public string DatabaseSchemaFileName { get { return _databaseSchemaFileName; } set { _databaseSchemaFileName = value; } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "Whether or not the extension should be used. N.B. If it is to be used, then the ExtensionAssemblyName as well as the full type names of the extensions need to be configured.", Visible = false, CategorySequenceId = 13)] public bool UseExtensions { get { return _useExtensions; } set { _useExtensions = value; } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "The name of the assembly (DLL file) containing the Figlut Desktop DataBox extension e.g. FiglutExtension.dll. The assembly needs to be placed in the Figlut Desktop DataBox executing directory.", Visible = false, CategorySequenceId = 14)] public string ExtensionAssemblyName { get { return _extensionAssemblyName; } set { _extensionAssemblyName = value; } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "The full type name of the class acting as the CRUD interceptor e.g. FiglutExtension.MyDesktopDataBoxCrudInterceptor.", Visible = false, CategorySequenceId = 15)] public string CrudInterceptorFullTypeName { get { return _crudInterceptorFullTypeName; } set { _crudInterceptorFullTypeName = value; } } [SettingInfo("DataBox", AutoFormatDisplayName = true, Description = "The full type name of the class acting as the main menu extension e.g. FiglutExtension.MyDesktopDataBoxMainMenuExtension.", Visible = false, CategorySequenceId = 16)] public string MainMenuExtentionFullTypeName { get { return _mainMenuExtensionFullTypeName; } set { _mainMenuExtensionFullTypeName = value; } } #endregion //DataBox #region Logging [SettingInfo("Logging", DisplayName = "To File", Description = "Whether or not to log to a text log file in the executing directory.", CategorySequenceId = 0)] public bool LogToFile { get { return _logToFile; } set { _logToFile = value; } } [SettingInfo("Logging", AutoFormatDisplayName = true, Description = "The name of the text log file to log to. The log file is written in the executing directory.", CategorySequenceId = 4)] public string LogFileName { get { return _logFileName; } set { _logFileName = value; } } [SettingInfo("Logging", AutoFormatDisplayName = true, Description = "The extent of messages being logged: None = logging is disabled, Minimum = logs server start/stop and exceptions, Normal = logs additional information messages, Maximum = logs all requests and responses to the server.", CategorySequenceId = 5)] public LoggingLevel LoggingLevel { get { return _loggingLevel; } set { _loggingLevel = value; } } #endregion //Logging #endregion //Properties #region Methods public List<Type> GetHiddenTypes() { return this._hiddenTypes; } protected void RefreshHiddenTypes() { if (this._hiddenTypes == null) { this._hiddenTypes = new List<Type>(); } this._hiddenTypes.Clear(); foreach (string str in this._hiddenTypeNames) { Type item = Type.GetType(str, false); if (item == null) { throw new NullReferenceException(string.Format("Could not find type {0} to add as a hidden type. Ensure that it is a fully qualified type name.", str)); } this._hiddenTypes.Add(item); } } public void ResetSettingsCategory(string categoryName) { if (categoryName == "Web Service") { ResetWebServiceSettingsCategory (); } else if (categoryName == "DataBox") { ResetDataBoxSettingsCategory (); } else if (categoryName == "Logging") { ResetLoggingSettingsCategory (); } else { throw new UserThrownException ( string.Format ("No settings with the category name {0} was found to be reset.", categoryName), LoggingLevel.Minimum); } } public void ResetAllSettings() { ResetWebServiceSettingsCategory (); ResetDataBoxSettingsCategory (); ResetLoggingSettingsCategory (); } private void ResetWebServiceSettingsCategory() { ShowMessageBoxOnException = true; FiglutWebServiceBaseUrl = "http://HostnameOrIpAddress:2983/Figlut/"; UseAuthentication = false; PromptForCredentials = false; AuthenticationDomainName = string.Empty; AuthenticationUserName = string.Empty; AuthenticationPassword = string.Empty; FiglutWebServiceWebRequestTimeout = 3000; FiglutWebServiceTextResponseEncoding = TextEncodingType.UTF8; FiglutWebServiceMessagingFormat = SerializerType.JSON; FiglutWebServiceSchemaAcquisitionMessagingFormat = SerializerType.XML; OfflineMode = false; } public void ResetDataBoxSettingsCategory() { ApplicationTitle = "Figlut Android DataBox"; ApplicationVersion = "1.0.0.0"; ThemeColor = ColorName.SteelBlue; ApplicationBannerImageFilePath = null; ShapeColumnNames = true; PrimaryColumnIndex = 1; SecondaryColumnIndex = 2; HiddenTypeNames = new List<string> () { typeof(Guid).FullName, typeof(Nullable<Guid>).FullName, typeof(Byte[]).FullName }; EntityIdColumnName = "ENTITY_ID_A2382C02EF06497A9BBFE4DB3C8290A8"; HideEntityIdColumn = true; TreatZeroAsNull = true; CloseAddWindowAfterAdd = false; DatabaseSchemaFileName = "FiglutDatabaseSchema.json"; UseExtensions = false; ExtensionAssemblyName = "Figlut.Extensions.dll"; CrudInterceptorFullTypeName = "Figlut.Extensions.CrudInterceptor"; MainMenuExtentionFullTypeName = "Figlut.Extensions.MainMenuExtension"; } public void ResetLoggingSettingsCategory() { LogToFile = true; LogFileName = "Figlut.MonoDroid.DataBox.Log.txt"; LoggingLevel = LoggingLevel.Maximum; } public void ResetDatabaseSchemaFileName() { DatabaseSchemaFileName = "FiglutDatabaseSchema.json"; } #endregion //Methods } }
// 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.Runtime; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Xml; namespace System.ServiceModel.Dispatcher { internal class StreamFormatter { private string _wrapperName; private string _wrapperNS; private string _partName; private string _partNS; private int _streamIndex; private bool _isRequest; private string _operationName; private const int returnValueIndex = -1; internal static StreamFormatter Create(MessageDescription messageDescription, string operationName, bool isRequest) { MessagePartDescription streamPart = ValidateAndGetStreamPart(messageDescription, isRequest, operationName); if (streamPart == null) return null; return new StreamFormatter(messageDescription, streamPart, operationName, isRequest); } private StreamFormatter(MessageDescription messageDescription, MessagePartDescription streamPart, string operationName, bool isRequest) { if ((object)streamPart == (object)messageDescription.Body.ReturnValue) _streamIndex = returnValueIndex; else _streamIndex = streamPart.Index; _wrapperName = messageDescription.Body.WrapperName; _wrapperNS = messageDescription.Body.WrapperNamespace; _partName = streamPart.Name; _partNS = streamPart.Namespace; _isRequest = isRequest; _operationName = operationName; } internal void Serialize(XmlDictionaryWriter writer, object[] parameters, object returnValue) { Stream streamValue = GetStreamAndWriteStartWrapperIfNecessary(writer, parameters, returnValue); var streamProvider = new OperationStreamProvider(streamValue); StreamFormatterHelper.WriteValue(writer, streamProvider); WriteEndWrapperIfNecessary(writer); } internal async Task SerializeAsync(XmlDictionaryWriter writer, object[] parameters, object returnValue) { Stream streamValue = await GetStreamAndWriteStartWrapperIfNecessaryAsync(writer, parameters, returnValue); var streamProvider = new OperationStreamProvider(streamValue); await StreamFormatterHelper.WriteValueAsync(writer, streamProvider); await WriteEndWrapperIfNecessaryAsync(writer); } private Stream GetStreamAndWriteStartWrapperIfNecessary(XmlDictionaryWriter writer, object[] parameters, object returnValue) { Stream streamValue = GetStreamValue(parameters, returnValue); if (streamValue == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(_partName); if (WrapperName != null) writer.WriteStartElement(WrapperName, WrapperNamespace); writer.WriteStartElement(PartName, PartNamespace); return streamValue; } private async Task<Stream> GetStreamAndWriteStartWrapperIfNecessaryAsync(XmlDictionaryWriter writer, object[] parameters, object returnValue) { Stream streamValue = GetStreamValue(parameters, returnValue); if (streamValue == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(_partName); if (WrapperName != null) await writer.WriteStartElementAsync(null, WrapperName, WrapperNamespace); await writer.WriteStartElementAsync(null, PartName, PartNamespace); return streamValue; } private void WriteEndWrapperIfNecessary(XmlDictionaryWriter writer) { writer.WriteEndElement(); if (_wrapperName != null) writer.WriteEndElement(); } private Task WriteEndWrapperIfNecessaryAsync(XmlDictionaryWriter writer) { writer.WriteEndElement(); if (_wrapperName != null) writer.WriteEndElement(); return Task.CompletedTask; } internal IAsyncResult BeginSerialize(XmlDictionaryWriter writer, object[] parameters, object returnValue, AsyncCallback callback, object state) { return new SerializeAsyncResult(this, writer, parameters, returnValue, callback, state); } public void EndSerialize(IAsyncResult result) { SerializeAsyncResult.End(result); } internal class SerializeAsyncResult : AsyncResult { private static AsyncCompletion s_handleEndSerialize = new AsyncCompletion(HandleEndSerialize); private StreamFormatter _streamFormatter; private XmlDictionaryWriter _writer; internal SerializeAsyncResult(StreamFormatter streamFormatter, XmlDictionaryWriter writer, object[] parameters, object returnValue, AsyncCallback callback, object state) : base(callback, state) { _streamFormatter = streamFormatter; _writer = writer; // As we use the Task-returning method for async operation, // we shouldn't get to this point. Throw exception just in case. throw ExceptionHelper.AsError(NotImplemented.ByDesign); } private static bool HandleEndSerialize(IAsyncResult result) { SerializeAsyncResult thisPtr = (SerializeAsyncResult)result.AsyncState; thisPtr._streamFormatter.WriteEndWrapperIfNecessary(thisPtr._writer); return true; } public static void End(IAsyncResult result) { AsyncResult.End<SerializeAsyncResult>(result); } } internal void Deserialize(object[] parameters, ref object retVal, Message message) { SetStreamValue(parameters, ref retVal, new MessageBodyStream(message, WrapperName, WrapperNamespace, PartName, PartNamespace, _isRequest)); } internal string WrapperName { get { return _wrapperName; } set { _wrapperName = value; } } internal string WrapperNamespace { get { return _wrapperNS; } set { _wrapperNS = value; } } internal string PartName { get { return _partName; } } internal string PartNamespace { get { return _partNS; } } private Stream GetStreamValue(object[] parameters, object returnValue) { if (_streamIndex == returnValueIndex) return (Stream)returnValue; return (Stream)parameters[_streamIndex]; } private void SetStreamValue(object[] parameters, ref object returnValue, Stream streamValue) { if (_streamIndex == returnValueIndex) returnValue = streamValue; else parameters[_streamIndex] = streamValue; } private static MessagePartDescription ValidateAndGetStreamPart(MessageDescription messageDescription, bool isRequest, string operationName) { MessagePartDescription part = GetStreamPart(messageDescription); if (part != null) return part; if (HasStream(messageDescription)) { if (messageDescription.IsTypedMessage) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStreamInTypedMessage, messageDescription.MessageName))); else if (isRequest) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStreamInRequest, operationName))); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStreamInResponse, operationName))); } return null; } private static bool HasStream(MessageDescription messageDescription) { if (messageDescription.Body.ReturnValue != null && messageDescription.Body.ReturnValue.Type == typeof(Stream)) return true; foreach (MessagePartDescription part in messageDescription.Body.Parts) { if (part.Type == typeof(Stream)) return true; } return false; } private static MessagePartDescription GetStreamPart(MessageDescription messageDescription) { if (OperationFormatter.IsValidReturnValue(messageDescription.Body.ReturnValue)) { if (messageDescription.Body.Parts.Count == 0) if (messageDescription.Body.ReturnValue.Type == typeof(Stream)) return messageDescription.Body.ReturnValue; } else { if (messageDescription.Body.Parts.Count == 1) if (messageDescription.Body.Parts[0].Type == typeof(Stream)) return messageDescription.Body.Parts[0]; } return null; } internal static bool IsStream(MessageDescription messageDescription) { return GetStreamPart(messageDescription) != null; } internal class MessageBodyStream : Stream { private Message _message; private XmlDictionaryReader _reader; private BufferedReadStream _bufferedReadStream; private long _position; private string _wrapperName, _wrapperNs; private string _elementName, _elementNs; private bool _isRequest; internal MessageBodyStream(Message message, string wrapperName, string wrapperNs, string elementName, string elementNs, bool isRequest) { _message = message; _position = 0; _wrapperName = wrapperName; _wrapperNs = wrapperNs; _elementName = elementName; _elementNs = elementNs; _isRequest = isRequest; } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (_reader == null) { if (_message.Properties.ContainsKey(BufferedReadStream.BufferedReadStreamPropertyName)) { _bufferedReadStream = _message.Properties[BufferedReadStream.BufferedReadStreamPropertyName] as BufferedReadStream; } } using (TaskHelpers.RunTaskContinuationsOnOurThreads()) { if (_bufferedReadStream != null) { await _bufferedReadStream.PreReadBufferAsync(cancellationToken); } return Read(buffer, offset, count); } } public override int Read(byte[] buffer, int offset, int count) { EnsureStreamIsOpen(); if (buffer == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("buffer"), _message); if (offset < 0) throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", offset, SR.Format(SR.ValueMustBeNonNegative)), _message); if (count < 0) throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", count, SR.Format(SR.ValueMustBeNonNegative)), _message); if (buffer.Length - offset < count) throw TraceUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.SFxInvalidStreamOffsetLength, offset + count)), _message); try { if (_reader == null) { _reader = _message.GetReaderAtBodyContents(); if (_wrapperName != null) { _reader.MoveToContent(); _reader.ReadStartElement(_wrapperName, _wrapperNs); } _reader.MoveToContent(); if (_reader.NodeType == XmlNodeType.EndElement) { return 0; } _reader.ReadStartElement(_elementName, _elementNs); } if (_reader.MoveToContent() != XmlNodeType.Text) { Exhaust(_reader); return 0; } int bytesRead = _reader.ReadContentAsBase64(buffer, offset, count); _position += bytesRead; if (bytesRead == 0) { Exhaust(_reader); } return bytesRead; } catch (Exception ex) { if (Fx.IsFatal(ex)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new IOException(SR.Format(SR.SFxStreamIOException), ex)); } } private void EnsureStreamIsOpen() { if (_message.State == MessageState.Closed) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(SR.Format( _isRequest ? SR.SFxStreamRequestMessageClosed : SR.SFxStreamResponseMessageClosed))); } private static void Exhaust(XmlDictionaryReader reader) { if (reader != null) { while (reader.Read()) { // drain } } } public override long Position { get { EnsureStreamIsOpen(); return _position; } set { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); } } protected override void Dispose(bool isDisposing) { _message.Close(); if (_reader != null) { _reader.Dispose(); _reader = null; } base.Dispose(isDisposing); } public override bool CanRead { get { return _message.State != MessageState.Closed; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); } } public override void Flush() { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); } public override long Seek(long offset, SeekOrigin origin) { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); } public override void SetLength(long value) { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); } public override void Write(byte[] buffer, int offset, int count) { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); } } internal class OperationStreamProvider { private Stream _stream; internal OperationStreamProvider(Stream stream) { _stream = stream; } public Stream GetStream() { return _stream; } public void ReleaseStream(Stream stream) { //Noop } } internal class StreamFormatterHelper { // The method was duplicated from the desktop implementation of // System.Xml.XmlDictionaryWriter.WriteValue(IStreamProvider) public static void WriteValue(XmlDictionaryWriter writer, OperationStreamProvider value) { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); Stream stream = value.GetStream(); if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.XmlInvalidStream))); } int blockSize = 256; int bytesRead = 0; byte[] block = new byte[blockSize]; while (true) { bytesRead = stream.Read(block, 0, blockSize); if (bytesRead > 0) { writer.WriteBase64(block, 0, bytesRead); } else { break; } if (blockSize < 65536 && bytesRead == blockSize) { blockSize = blockSize * 16; block = new byte[blockSize]; } } value.ReleaseStream(stream); } public static async Task WriteValueAsync(XmlDictionaryWriter writer, OperationStreamProvider value) { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); Stream stream = value.GetStream(); if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.XmlInvalidStream))); } int blockSize = 256; int bytesRead = 0; byte[] block = new byte[blockSize]; while (true) { bytesRead = await stream.ReadAsync(block, 0, blockSize); if (bytesRead > 0) { // XmlDictionaryWriter has not implemented WriteBase64Async() yet. writer.WriteBase64(block, 0, bytesRead); } else { break; } if (blockSize < 65536 && bytesRead == blockSize) { blockSize = blockSize * 16; block = new byte[blockSize]; } } value.ReleaseStream(stream); } } } }
using System; using UnityEngine; using System.Linq; using System.IO; using System.Text.RegularExpressions; using System.Collections.Generic; using Object = UnityEngine.Object; namespace UnityEditor.UI.Windows.Extensions.Utilities { internal class NewScriptGenerator { private const int kCommentWrapLength = 35; private TextWriter m_Writer; private string m_Text; private ScriptPrescription m_ScriptPrescription; private string m_Indentation; private int m_IndentLevel = 0; private int IndentLevel { get { return m_IndentLevel; } set { m_IndentLevel = value; m_Indentation = String.Empty; for (int i = 0; i < m_IndentLevel; i++) m_Indentation += " "; } } private string ClassName { get { if (m_ScriptPrescription.m_ClassName != string.Empty) return m_ScriptPrescription.m_ClassName; return "Example"; } } public NewScriptGenerator(ScriptPrescription scriptPrescription) { m_ScriptPrescription = scriptPrescription; } public override string ToString() { m_Text = m_ScriptPrescription.m_Template; m_Writer = new StringWriter(); m_Writer.NewLine = "\n"; // Make sure all line endings are Unix (Mac OS X) format m_Text = Regex.Replace(m_Text, @"\r\n?", delegate(Match m) { return "\n"; }); // Class Name m_Text = m_Text.Replace("$ClassName", ClassName); m_Text = m_Text.Replace("$NicifiedClassName", ObjectNames.NicifyVariableName(ClassName)); // Other replacements foreach (KeyValuePair<string, string> kvp in m_ScriptPrescription.m_StringReplacements) m_Text = m_Text.Replace(kvp.Key, kvp.Value); // Functions // Find $Functions keyword including leading tabs Match match = Regex.Match(m_Text, @"(\t*)\$Functions"); if (match.Success) { // Set indent level to number of tabs before $Functions keyword IndentLevel = match.Groups[1].Value.Length; bool hasFunctions = false; if (m_ScriptPrescription.m_Functions != null) { foreach (var function in m_ScriptPrescription.m_Functions.Where (f => f.include)) { WriteFunction(function); WriteBlankLine(); hasFunctions = true; } // Replace $Functions keyword plus newline with generated functions text if (hasFunctions) m_Text = m_Text.Replace(match.Value + "\n", m_Writer.ToString()); } if (!hasFunctions) { /*if (m_ScriptPrescription.m_Lang == Language.Boo && !m_Text.Contains ("def")) // Replace $Functions keyword with "pass" if no functions in Boo m_Text = m_Text.Replace (match.Value, m_Indentation + "pass"); else*/ // Otherwise just remove $Functions keyword plus newline m_Text = m_Text.Replace(match.Value + "\n", string.Empty); } } // Put curly vraces on new line if specified in editor prefs if (EditorPrefs.GetBool("CurlyBracesOnNewLine")) PutCurveBracesOnNewLine(); // Return the text of the script return m_Text; } private void PutCurveBracesOnNewLine() { m_Text = Regex.Replace(m_Text, @"(\t*)(.*) {\n((\t*)\n(\t*))?", delegate(Match match) { return match.Groups[1].Value + match.Groups[2].Value + "\n" + match.Groups[1].Value + "{\n" + (match.Groups[4].Value == match.Groups[5].Value ? match.Groups[4].Value : match.Groups[3].Value); }); } private void WriteBlankLine() { m_Writer.WriteLine(m_Indentation); } private void WriteComment(string comment) { int index = 0; while (true) { if (comment.Length <= index + kCommentWrapLength) { m_Writer.WriteLine(m_Indentation + "// " + comment.Substring(index)); break; } else { int wrapIndex = comment.IndexOf(' ', index + kCommentWrapLength); if (wrapIndex < 0) { m_Writer.WriteLine(m_Indentation + "// " + comment.Substring(index)); break; } else { m_Writer.WriteLine(m_Indentation + "// " + comment.Substring(index, wrapIndex - index)); index = wrapIndex + 1; } } } } private string TranslateTypeToJavascript(string typeInCSharp) { return typeInCSharp.Replace("bool", "boolean").Replace("string", "String").Replace("Object", "UnityEngine.Object"); } private string TranslateTypeToBoo(string typeInCSharp) { return typeInCSharp.Replace("float", "single"); } private void WriteFunction(FunctionData function) { string paramString = string.Empty; string overrideString; string returnTypeString; string functionContentString; string paramStringWithoutTypes = string.Empty; switch (m_ScriptPrescription.m_Lang) { /*case Language.JavaScript: // Comment WriteComment (function.comment); // Function header for (int i=0; i<function.parameters.Length; i++) { paramString += function.parameters[i].name + " : " + TranslateTypeToJavascript (function.parameters[i].type); if (i < function.parameters.Length-1) paramString += ", "; } overrideString = (function.isVirtual ? "override " : string.Empty); returnTypeString = (function.returnType == null ? " " : " : " + TranslateTypeToJavascript (function.returnType) + " "); m_Writer.WriteLine (m_Indentation + overrideString + "function " + function.name + " (" + paramString + ")" + returnTypeString + "{"); // Function content IndentLevel++; functionContentString = (function.returnType == null ? string.Empty : function.returnDefault + ";"); m_Writer.WriteLine (m_Indentation + functionContentString); IndentLevel--; m_Writer.WriteLine (m_Indentation + "}"); break;*/ case Language.CSharp: // Comment WriteComment(function.comment); // Function header for (int i = 0; i < function.parameters.Length; i++) { paramString += function.parameters[i].type + " " + function.parameters[i].name; paramStringWithoutTypes += function.parameters[i].name; if (i < function.parameters.Length - 1) { paramString += ", "; paramStringWithoutTypes += ", "; } } overrideString = (function.isVirtual ? "public override " : string.Empty); returnTypeString = (function.returnType == null ? "void " : function.returnType + " "); m_Writer.WriteLine(m_Indentation + overrideString + returnTypeString + function.name + "(" + paramString + ") {"); // Function content IndentLevel++; { if (function.isVirtual == true) { WriteBlankLine(); m_Writer.WriteLine(m_Indentation + "base." + function.name + "(" + paramStringWithoutTypes + ");"); WriteBlankLine(); } functionContentString = (function.returnType == null ? string.Empty : function.returnDefault + ";"); m_Writer.WriteLine(m_Indentation + functionContentString); WriteBlankLine(); } IndentLevel--; m_Writer.WriteLine(m_Indentation + "}"); break; /*case Language.Boo: // Comment WriteComment (function.comment); // Function header for (int i=0; i<function.parameters.Length; i++) { paramString += function.parameters[i].name + " as " + TranslateTypeToBoo (function.parameters[i].type); if (i < function.parameters.Length-1) paramString += ", "; } overrideString = (function.isVirtual ? "public override " : string.Empty); returnTypeString = (function.returnType == null ? string.Empty : " as " + TranslateTypeToJavascript (function.returnType)); m_Writer.WriteLine (m_Indentation + overrideString + "def " + function.name + " (" + paramString + ")" + returnTypeString + ":"); // Function content IndentLevel++; functionContentString = (function.returnType == null ? "pass" : function.returnDefault); m_Writer.WriteLine (m_Indentation + functionContentString); IndentLevel--; break;*/ } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SMTP.Relay { #region usings using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Threading; using Log; using TCP; #endregion #region Delegates /// <summary> /// Represents the method that will handle the <b>Relay_Server.SessionCompleted</b> event. /// </summary> /// <param name="e">Event data.</param> public delegate void Relay_SessionCompletedEventHandler(Relay_SessionCompletedEventArgs e); #endregion /// <summary> /// This class implements SMTP relay server. Defined in RFC 2821. /// </summary> public class Relay_Server : IDisposable { #region Events /// <summary> /// This event is raised when unhandled exception happens. /// </summary> public event ErrorEventHandler Error = null; /// <summary> /// This event is raised when relay session processing completes. /// </summary> public event Relay_SessionCompletedEventHandler SessionCompleted = null; #endregion #region Members private bool m_HasBindingsChanged; private bool m_IsDisposed; private bool m_IsRunning; private long m_MaxConnections; private long m_MaxConnectionsPerIP; private IPBindInfo[] m_pBindings = new IPBindInfo[0]; private Dictionary<IPAddress, long> m_pConnectionsPerIP; private CircleCollection<IPBindInfo> m_pLocalEndPoints; private List<Relay_Queue> m_pQueues; private TCP_SessionCollection<Relay_Session> m_pSessions; private CircleCollection<Relay_SmartHost> m_pSmartHosts; private Relay_Mode m_RelayMode = Relay_Mode.Dns; private int m_SessionIdleTimeout = 30; private BalanceMode m_SmartHostsBalanceMode = BalanceMode.LoadBalance; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public Relay_Server() { m_pQueues = new List<Relay_Queue>(); m_pSmartHosts = new CircleCollection<Relay_SmartHost>(); } #endregion #region Properties /// <summary> /// Gets or sets relay server IP bindings. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public IPBindInfo[] Bindings { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pBindings; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value == null) { value = new IPBindInfo[0]; } //--- See binds has changed -------------- bool changed = false; if (m_pBindings.Length != value.Length) { changed = true; } else { for (int i = 0; i < m_pBindings.Length; i++) { if (!m_pBindings[i].Equals(value[i])) { changed = true; break; } } } if (changed) { m_pBindings = value; m_HasBindingsChanged = true; } } } /// <summary> /// Gets if server is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets if server is running. /// </summary> public bool IsRunning { get { return m_IsRunning; } } /// <summary> /// Gets or sets relay logger. Value null means no logging. /// </summary> public Logger Logger { get; set; } /// <summary> /// Gets or sets maximum allowed concurent connections. Value 0 means unlimited. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when negative value is passed.</exception> public long MaxConnections { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MaxConnections; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value < 0) { throw new ArgumentException("Property 'MaxConnections' value must be >= 0."); } m_MaxConnections = value; } } /// <summary> /// Gets or sets maximum allowed connections to 1 IP address. Value 0 means unlimited. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public long MaxConnectionsPerIP { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_MaxConnectionsPerIP; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_MaxConnectionsPerIP < 0) { throw new ArgumentException("Property 'MaxConnectionsPerIP' value must be >= 0."); } m_MaxConnectionsPerIP = value; } } /// <summary> /// Gets relay queues. Queue with lower index number has higher priority. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public List<Relay_Queue> Queues { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pQueues; } } /// <summary> /// Gets or sets relay mode. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public Relay_Mode RelayMode { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_RelayMode; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } m_RelayMode = value; } } /// <summary> /// Gets or sets session idle time in seconds when it will be timed out. Value 0 means unlimited (strongly not recomended). /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception> public int SessionIdleTimeout { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_SessionIdleTimeout; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_SessionIdleTimeout < 0) { throw new ArgumentException("Property 'SessionIdleTimeout' value must be >= 0."); } m_SessionIdleTimeout = value; } } /// <summary> /// Gets active relay sessions. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when this property is accessed and relay server is not running.</exception> public TCP_SessionCollection<Relay_Session> Sessions { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!m_IsRunning) { throw new InvalidOperationException("Relay server not running."); } return m_pSessions; } } /// <summary> /// Gets or sets smart hosts. Smart hosts must be in priority order, lower index number means higher priority. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when null value is passed.</exception> public Relay_SmartHost[] SmartHosts { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pSmartHosts.ToArray(); } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (value == null) { throw new ArgumentNullException("SmartHosts"); } m_pSmartHosts.Add(value); } } /// <summary> /// Gets or sets how smart hosts will be balanced. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> public BalanceMode SmartHostsBalanceMode { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_SmartHostsBalanceMode; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } m_SmartHostsBalanceMode = value; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } try { if (m_IsRunning) { Stop(); } } catch {} m_IsDisposed = true; // Release events. Error = null; SessionCompleted = null; m_pQueues = null; m_pSmartHosts = null; } /// <summary> /// Starts SMTP relay server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public virtual void Start() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (m_IsRunning) { return; } m_IsRunning = true; m_pLocalEndPoints = new CircleCollection<IPBindInfo>(); m_pSessions = new TCP_SessionCollection<Relay_Session>(); m_pConnectionsPerIP = new Dictionary<IPAddress, long>(); Thread tr1 = new Thread(Run); tr1.Start(); Thread tr2 = new Thread(Run_CheckTimedOutSessions); tr2.Start(); } /// <summary> /// Stops SMTP relay server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> public virtual void Stop() { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!m_IsRunning) { return; } m_IsRunning = false; // TODO: We need to send notify to all not processed messages, then they can be Disposed as needed. // Clean up. m_pLocalEndPoints = null; //m_pSessions.Dispose(); m_pSessions = null; m_pConnectionsPerIP = null; } #endregion #region Virtual methods /// <summary> /// Raises <b>SessionCompleted</b> event. /// </summary> /// <param name="session">Session what completed processing.</param> /// <param name="exception">Exception happened or null if relay completed successfully.</param> protected internal virtual void OnSessionCompleted(Relay_Session session, Exception exception) { if (SessionCompleted != null) { SessionCompleted(new Relay_SessionCompletedEventArgs(session, exception)); } } /// <summary> /// Raises <b>Error</b> event. /// </summary> /// <param name="x">Exception happned.</param> protected internal virtual void OnError(Exception x) { if (Error != null) { Error(this, new Error_EventArgs(x, new StackTrace())); } } #endregion #region Internal methods /// <summary> /// Increases specified IP address connactions count if maximum allowed connections to /// the specified IP address isn't exceeded. /// </summary> /// <param name="ip">IP address.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception> /// <returns>Returns true if specified IP usage increased, false if maximum allowed connections to the specified IP address is exceeded.</returns> internal bool TryAddIpUsage(IPAddress ip) { if (ip == null) { throw new ArgumentNullException("ip"); } lock (m_pConnectionsPerIP) { long count = 0; // Specified IP entry exists, increase usage. if (m_pConnectionsPerIP.TryGetValue(ip, out count)) { // Maximum allowed connections to the specified IP address is exceeded. if (m_MaxConnectionsPerIP > 0 && count >= m_MaxConnectionsPerIP) { return false; } m_pConnectionsPerIP[ip] = count + 1; } // Specified IP entry doesn't exist, create new entry and increase usage. else { m_pConnectionsPerIP.Add(ip, 1); } return true; } } /// <summary> /// Decreases specified IP address connactions count. /// </summary> /// <param name="ip">IP address.</param> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception> internal void RemoveIpUsage(IPAddress ip) { if (ip == null) { throw new ArgumentNullException("ip"); } lock (m_pConnectionsPerIP) { long count = 0; // Specified IP entry exists, increase usage. if (m_pConnectionsPerIP.TryGetValue(ip, out count)) { // This is last usage to that IP, remove that IP entry. if (count == 1) { m_pConnectionsPerIP.Remove(ip); } // Decrease Ip usage. else { m_pConnectionsPerIP[ip] = count - 1; } } else { // No such entry, just skip it. } } } /// <summary> /// Gets how many connections to the specified IP address. /// </summary> /// <param name="ip">IP address.</param> /// <returns>Returns number of connections to the specified IP address.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception> internal long GetIpUsage(IPAddress ip) { if (ip == null) { throw new ArgumentNullException("ip"); } lock (m_pConnectionsPerIP) { long count = 0; // Specified IP entry exists, return usage. if (m_pConnectionsPerIP.TryGetValue(ip, out count)) { return count; } // No usage to specified IP. else { return 0; } } } #endregion #region Utility methods /// <summary> /// Processes relay queue. /// </summary> private void Run() { while (m_IsRunning) { try { // Bind info has changed, create new local end points. if (m_HasBindingsChanged) { m_pLocalEndPoints.Clear(); foreach (IPBindInfo binding in m_pBindings) { if (binding.IP == IPAddress.Any) { foreach (IPAddress ip in Dns.GetHostAddresses("")) { if (ip.AddressFamily == AddressFamily.InterNetwork) { IPBindInfo b = new IPBindInfo(binding.HostName, binding.Protocol, ip, 25); if (!m_pLocalEndPoints.Contains(b)) { m_pLocalEndPoints.Add(b); } } } } else if (binding.IP == IPAddress.IPv6Any) { foreach (IPAddress ip in Dns.GetHostAddresses("")) { if (ip.AddressFamily == AddressFamily.InterNetworkV6) { IPBindInfo b = new IPBindInfo(binding.HostName, binding.Protocol, ip, 25); if (!m_pLocalEndPoints.Contains(b)) { m_pLocalEndPoints.Add(b); } } } } else { IPBindInfo b = new IPBindInfo(binding.HostName, binding.Protocol, binding.IP, 25); if (!m_pLocalEndPoints.Contains(b)) { m_pLocalEndPoints.Add(b); } } } m_HasBindingsChanged = false; } // There are no local end points specified. if (m_pLocalEndPoints.Count == 0) { Thread.Sleep(10); } // Maximum allowed relay sessions exceeded, skip adding new ones. else if (m_MaxConnections != 0 && m_pSessions.Count >= m_MaxConnections) { Thread.Sleep(10); } else { Relay_QueueItem item = null; // Get next queued message from highest possible priority queue. foreach (Relay_Queue queue in m_pQueues) { item = queue.DequeueMessage(); // There is queued message. if (item != null) { break; } // No messages in this queue, see next lower priority queue. } // There are no messages in any queue. if (item == null) { Thread.Sleep(10); } // Create new session for queued relay item. else { // Get round-robin local end point for that session. // This ensures if multiple network connections, all will be load balanced. IPBindInfo localBindInfo = m_pLocalEndPoints.Next(); if (m_RelayMode == Relay_Mode.Dns) { Relay_Session session = new Relay_Session(this, localBindInfo, item); m_pSessions.Add(session); ThreadPool.QueueUserWorkItem(session.Start); } else if (m_RelayMode == Relay_Mode.SmartHost) { // Get smart hosts in balance mode order. Relay_SmartHost[] smartHosts = null; if (m_SmartHostsBalanceMode == BalanceMode.FailOver) { smartHosts = m_pSmartHosts.ToArray(); } else { smartHosts = m_pSmartHosts.ToCurrentOrderArray(); } Relay_Session session = new Relay_Session(this, localBindInfo, item, smartHosts); m_pSessions.Add(session); ThreadPool.QueueUserWorkItem(session.Start); } } } } catch (Exception x) { OnError(x); } } } /// <summary> /// This method checks timed out relay sessions while server is running. /// </summary> private void Run_CheckTimedOutSessions() { DateTime lastCheck = DateTime.Now; while (IsRunning) { try { // Check interval reached. if (m_SessionIdleTimeout > 0 && lastCheck.AddSeconds(30) < DateTime.Now) { foreach (Relay_Session session in Sessions.ToArray()) { try { if (session.LastActivity.AddSeconds(m_SessionIdleTimeout) < DateTime.Now) { session.Dispose(new Exception("Session idle timeout.")); } } catch {} } lastCheck = DateTime.Now; } // Not check interval yet. else { Thread.Sleep(1000); } } catch (Exception x) { OnError(x); } } } #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.Linq; using System.Collections; using System.IO; using System.Runtime.InteropServices; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class CollectionTests { [Fact] public static void X509CertificateCollectionsProperties() { IList ilist = new X509CertificateCollection(); Assert.False(ilist.IsSynchronized); Assert.False(ilist.IsFixedSize); Assert.False(ilist.IsReadOnly); ilist = new X509Certificate2Collection(); Assert.False(ilist.IsSynchronized); Assert.False(ilist.IsFixedSize); Assert.False(ilist.IsReadOnly); } [Fact] public static void X509CertificateCollectionConstructors() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); X509CertificateCollection cc2 = new X509CertificateCollection(cc); Assert.Equal(3, cc2.Count); Assert.Same(c1, cc2[0]); Assert.Same(c2, cc2[1]); Assert.Same(c3, cc2[2]); Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection(new X509Certificate[] { c1, c2, null, c3 })); } } [Fact] public static void X509Certificate2CollectionConstructors() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); X509Certificate2Collection cc2 = new X509Certificate2Collection(cc); Assert.Equal(3, cc2.Count); Assert.Same(c1, cc2[0]); Assert.Same(c2, cc2[1]); Assert.Same(c3, cc2[2]); Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection(new X509Certificate2[] { c1, c2, null, c3 })); using (X509Certificate c4 = new X509Certificate()) { X509Certificate2Collection collection = new X509Certificate2Collection { c1, c2, c3 }; ((IList)collection).Add(c4); // Add non-X509Certificate2 object Assert.Throws<InvalidCastException>(() => new X509Certificate2Collection(collection)); } } } [Fact] public static void X509Certificate2CollectionEnumerator() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); object ignored; X509Certificate2Enumerator e = cc.GetEnumerator(); for (int i = 0; i < 2; i++) { // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // Ended Assert.Throws<InvalidOperationException>(() => ignored = e.Current); e.Reset(); } IEnumerator e2 = cc.GetEnumerator(); TestNonGenericEnumerator(e2, c1, c2, c3); IEnumerator e3 = ((IEnumerable)cc).GetEnumerator(); TestNonGenericEnumerator(e3, c1, c2, c3); } } [Fact] public static void X509CertificateCollectionEnumerator() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); object ignored; X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator(); for (int i = 0; i < 2; i++) { // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // Ended Assert.Throws<InvalidOperationException>(() => ignored = e.Current); e.Reset(); } IEnumerator e2 = cc.GetEnumerator(); TestNonGenericEnumerator(e2, c1, c2, c3); IEnumerator e3 = ((IEnumerable)cc).GetEnumerator(); TestNonGenericEnumerator(e3, c1, c2, c3); } } private static void TestNonGenericEnumerator(IEnumerator e, object c1, object c2, object c3) { object ignored; for (int i = 0; i < 2; i++) { // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // Ended Assert.Throws<InvalidOperationException>(() => ignored = e.Current); e.Reset(); } } [Fact] public static void X509CertificateCollectionThrowsArgumentNullException() { using (X509Certificate certificate = new X509Certificate()) { Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection((X509Certificate[])null)); Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection((X509CertificateCollection)null)); X509CertificateCollection collection = new X509CertificateCollection { certificate }; Assert.Throws<ArgumentNullException>(() => collection[0] = null); Assert.Throws<ArgumentNullException>(() => collection.Add(null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate[])null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509CertificateCollection)null)); Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => collection.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => collection.Remove(null)); IList ilist = (IList)collection; Assert.Throws<ArgumentNullException>(() => ilist[0] = null); Assert.Throws<ArgumentNullException>(() => ilist.Add(null)); Assert.Throws<ArgumentNullException>(() => ilist.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => ilist.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => ilist.Remove(null)); } Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection.X509CertificateEnumerator(null)); } [Fact] public static void X509Certificate2CollectionThrowsArgumentNullException() { using (X509Certificate2 certificate = new X509Certificate2()) { Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection((X509Certificate2[])null)); Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection((X509Certificate2Collection)null)); X509Certificate2Collection collection = new X509Certificate2Collection { certificate }; Assert.Throws<ArgumentNullException>(() => collection[0] = null); Assert.Throws<ArgumentNullException>(() => collection.Add((X509Certificate)null)); Assert.Throws<ArgumentNullException>(() => collection.Add((X509Certificate2)null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate[])null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509CertificateCollection)null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate2[])null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate2Collection)null)); Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => collection.Insert(0, (X509Certificate)null)); Assert.Throws<ArgumentNullException>(() => collection.Insert(0, (X509Certificate2)null)); Assert.Throws<ArgumentNullException>(() => collection.Remove((X509Certificate)null)); Assert.Throws<ArgumentNullException>(() => collection.Remove((X509Certificate2)null)); Assert.Throws<ArgumentNullException>(() => collection.RemoveRange((X509Certificate2[])null)); Assert.Throws<ArgumentNullException>(() => collection.RemoveRange((X509Certificate2Collection)null)); Assert.Throws<ArgumentNullException>(() => collection.Import((byte[])null)); Assert.Throws<ArgumentNullException>(() => collection.Import((string)null)); IList ilist = (IList)collection; Assert.Throws<ArgumentNullException>(() => ilist[0] = null); Assert.Throws<ArgumentNullException>(() => ilist.Add(null)); Assert.Throws<ArgumentNullException>(() => ilist.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => ilist.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => ilist.Remove(null)); } } [Fact] public static void X509CertificateCollectionThrowsArgumentOutOfRangeException() { using (X509Certificate certificate = new X509Certificate()) { X509CertificateCollection collection = new X509CertificateCollection { certificate }; Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(collection.Count)); IList ilist = (IList)collection; Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(collection.Count)); } } [Fact] public static void X509Certificate2CollectionThrowsArgumentOutOfRangeException() { using (X509Certificate2 certificate = new X509Certificate2()) { X509Certificate2Collection collection = new X509Certificate2Collection { certificate }; Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(collection.Count)); IList ilist = (IList)collection; Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(collection.Count)); } } [Fact] public static void X509CertificateCollectionContains() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection collection = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); Assert.True(collection.Contains(c1)); Assert.True(collection.Contains(c2)); Assert.True(collection.Contains(c3)); Assert.False(collection.Contains(null)); IList ilist = (IList)collection; Assert.True(ilist.Contains(c1)); Assert.True(ilist.Contains(c2)); Assert.True(ilist.Contains(c3)); Assert.False(ilist.Contains(null)); Assert.False(ilist.Contains("Bogus")); } } [Fact] public static void X509Certificate2CollectionContains() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection collection = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); Assert.True(collection.Contains(c1)); Assert.True(collection.Contains(c2)); Assert.True(collection.Contains(c3)); // Note: X509Certificate2Collection.Contains used to throw ArgumentNullException, but it // has been deliberately changed to no longer throw to match the behavior of // X509CertificateCollection.Contains and the IList.Contains implementation, which do not // throw. Assert.False(collection.Contains(null)); IList ilist = (IList)collection; Assert.True(ilist.Contains(c1)); Assert.True(ilist.Contains(c2)); Assert.True(ilist.Contains(c3)); Assert.False(ilist.Contains(null)); Assert.False(ilist.Contains("Bogus")); } } [Fact] public static void X509CertificateCollectionEnumeratorModification() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator(); cc.Add(c1); // Collection changed. Assert.Throws<InvalidOperationException>(() => e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Reset()); } } [Fact] public static void X509Certificate2CollectionEnumeratorModification() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); X509Certificate2Enumerator e = cc.GetEnumerator(); cc.Add(c1); // Collection changed. Assert.Throws<InvalidOperationException>(() => e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Reset()); } } [Fact] public static void X509CertificateCollectionAdd() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) { X509CertificateCollection cc = new X509CertificateCollection(); int idx = cc.Add(c1); Assert.Equal(0, idx); Assert.Same(c1, cc[0]); idx = cc.Add(c2); Assert.Equal(1, idx); Assert.Same(c2, cc[1]); Assert.Throws<ArgumentNullException>(() => cc.Add(null)); IList il = new X509CertificateCollection(); idx = il.Add(c1); Assert.Equal(0, idx); Assert.Same(c1, il[0]); idx = il.Add(c2); Assert.Equal(1, idx); Assert.Same(c2, il[1]); Assert.Throws<ArgumentNullException>(() => il.Add(null)); } } [Fact] public static void X509CertificateCollectionAsIList() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) { IList il = new X509CertificateCollection(); il.Add(c1); il.Add(c2); Assert.Throws<ArgumentNullException>(() => il[0] = null); string bogus = "Bogus"; Assert.Throws<ArgumentException>(() => il[0] = bogus); Assert.Throws<ArgumentException>(() => il.Add(bogus)); Assert.Throws<ArgumentException>(() => il.Insert(0, bogus)); } } [Fact] public static void AddDoesNotClone() { using (X509Certificate2 c1 = new X509Certificate2()) { X509Certificate2Collection coll = new X509Certificate2Collection(); coll.Add(c1); Assert.Same(c1, coll[0]); } } [Fact] public static void ImportStoreSavedAsCerData() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsCerData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void ImportStoreSavedAsSerializedCerData_Windows() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsSerializedCerData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public static void ImportStoreSavedAsSerializedCerData_Unix() { X509Certificate2Collection cc2 = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => cc2.Import(TestData.StoreSavedAsSerializedCerData)); Assert.Equal(0, cc2.Count); } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void ImportStoreSavedAsSerializedStoreData_Windows() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsSerializedStoreData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); Assert.NotSame(msCer, cs[0]); Assert.Equal(msCer, cs[0]); Assert.Equal(msCer.Thumbprint, cs[0].Thumbprint); Assert.NotSame(pfxCer, cs[1]); Assert.Equal(pfxCer, cs[1]); Assert.Equal(pfxCer.Thumbprint, cs[1].Thumbprint); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public static void ImportStoreSavedAsSerializedStoreData_Unix() { X509Certificate2Collection cc2 = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => cc2.Import(TestData.StoreSavedAsSerializedStoreData)); Assert.Equal(0, cc2.Count); } [Fact] public static void ImportStoreSavedAsPfxData() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsPfxData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); Assert.NotSame(msCer, cs[0]); Assert.Equal(msCer, cs[0]); Assert.Equal(msCer.Thumbprint, cs[0].Thumbprint); Assert.NotSame(pfxCer, cs[1]); Assert.Equal(pfxCer, cs[1]); Assert.Equal(pfxCer.Thumbprint, cs[1].Thumbprint); } } [Fact] public static void ImportInvalidData() { X509Certificate2Collection cc2 = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => cc2.Import(new byte[] { 0, 1, 1, 2, 3, 5, 8, 13, 21 })); } [Fact] public static void ImportFromFileTests() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "My.pfx"), TestData.PfxDataPassword, X509KeyStorageFlags.DefaultKeySet)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } } [Fact] [ActiveIssue(2745, PlatformID.AnyUnix)] public static void ImportMultiplePrivateKeysPfx() { using (ImportedCollection ic = Cert.Import(TestData.MultiPrivateKeyPfx)) { X509Certificate2Collection collection = ic.Collection; Assert.Equal(2, collection.Count); foreach (X509Certificate2 cert in collection) { Assert.True(cert.HasPrivateKey, "cert.HasPrivateKey"); } } } [Fact] public static void ExportCert() { TestExportSingleCert(X509ContentType.Cert); } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void ExportSerializedCert_Windows() { TestExportSingleCert(X509ContentType.SerializedCert); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public static void ExportSerializedCert_Unix() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var ecdsa256Cer = new X509Certificate2(TestData.ECDsa256Certificate)) { X509Certificate2Collection cc = new X509Certificate2Collection(new[] { msCer, ecdsa256Cer }); Assert.Throws<PlatformNotSupportedException>(() => cc.Export(X509ContentType.SerializedCert)); } } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void ExportSerializedStore_Windows() { TestExportStore(X509ContentType.SerializedStore); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public static void ExportSerializedStore_Unix() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var ecdsa256Cer = new X509Certificate2(TestData.ECDsa256Certificate)) { X509Certificate2Collection cc = new X509Certificate2Collection(new[] { msCer, ecdsa256Cer }); Assert.Throws<PlatformNotSupportedException>(() => cc.Export(X509ContentType.SerializedStore)); } } [Fact] public static void ExportPkcs7() { TestExportStore(X509ContentType.Pkcs7); } [Fact] public static void X509CertificateCollectionSyncRoot() { var cc = new X509CertificateCollection(); Assert.NotNull(((ICollection)cc).SyncRoot); Assert.Same(((ICollection)cc).SyncRoot, ((ICollection)cc).SyncRoot); } [Fact] public static void ExportEmpty_Cert() { var collection = new X509Certificate2Collection(); byte[] exported = collection.Export(X509ContentType.Cert); Assert.Null(exported); } [Fact] [ActiveIssue(2746, PlatformID.AnyUnix)] public static void ExportEmpty_Pkcs12() { var collection = new X509Certificate2Collection(); byte[] exported = collection.Export(X509ContentType.Pkcs12); // The empty PFX is legal, the answer won't be null. Assert.NotNull(exported); } [Fact] public static void ExportUnrelatedPfx() { // Export multiple certificates which are not part of any kind of certificate chain. // Nothing in the PKCS12 structure requires they're related, but it might be an underlying // assumption of the provider. using (var cert1 = new X509Certificate2(TestData.MsCertificate)) using (var cert2 = new X509Certificate2(TestData.ComplexNameInfoCert)) using (var cert3 = new X509Certificate2(TestData.CertWithPolicies)) { var collection = new X509Certificate2Collection { cert1, cert2, cert3, }; byte[] exported = collection.Export(X509ContentType.Pkcs12); using (ImportedCollection ic = Cert.Import(exported)) { X509Certificate2Collection importedCollection = ic.Collection; // Verify that the two collections contain the same certificates, // but the order isn't really a factor. Assert.Equal(collection.Count, importedCollection.Count); // Compare just the subject names first, because it's the easiest thing to read out of the failure message. string[] subjects = new string[collection.Count]; string[] importedSubjects = new string[collection.Count]; for (int i = 0; i < collection.Count; i++) { subjects[i] = collection[i].GetNameInfo(X509NameType.SimpleName, false); importedSubjects[i] = importedCollection[i].GetNameInfo(X509NameType.SimpleName, false); } Assert.Equal(subjects, importedSubjects); // But, really, the collections should be equivalent // (after being coerced to IEnumerable<X509Certificate2>) Assert.Equal(collection.OfType<X509Certificate2>(), importedCollection.OfType<X509Certificate2>()); } } } [Fact] public static void MultipleImport() { var collection = new X509Certificate2Collection(); try { collection.Import(Path.Combine("TestData", "DummyTcpServer.pfx"), null, default(X509KeyStorageFlags)); collection.Import(TestData.PfxData, TestData.PfxDataPassword, default(X509KeyStorageFlags)); Assert.Equal(3, collection.Count); } finally { foreach (X509Certificate2 cert in collection) { cert.Dispose(); } } } [Fact] [ActiveIssue(2743, PlatformID.AnyUnix)] public static void ExportMultiplePrivateKeys() { var collection = new X509Certificate2Collection(); try { collection.Import(Path.Combine("TestData", "DummyTcpServer.pfx"), null, X509KeyStorageFlags.Exportable); collection.Import(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable); // Pre-condition, we have multiple private keys int originalPrivateKeyCount = collection.OfType<X509Certificate2>().Count(c => c.HasPrivateKey); Assert.Equal(2, originalPrivateKeyCount); // Export, re-import. byte[] exported; try { exported = collection.Export(X509ContentType.Pkcs12); } catch (PlatformNotSupportedException) { // [ActiveIssue(2743, PlatformID.AnyUnix)] // Our Unix builds can't export more than one private key in a single PFX, so this is // their exit point. // // If Windows gets here, or any exception other than PlatformNotSupportedException is raised, // let that fail the test. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw; } return; } // As the other half of issue 2743, if we make it this far we better be Windows (or remove the catch // above) Assert.True(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), "RuntimeInformation.IsOSPlatform(OSPlatform.Windows)"); using (ImportedCollection ic = Cert.Import(exported)) { X509Certificate2Collection importedCollection = ic.Collection; Assert.Equal(collection.Count, importedCollection.Count); int importedPrivateKeyCount = importedCollection.OfType<X509Certificate2>().Count(c => c.HasPrivateKey); Assert.Equal(originalPrivateKeyCount, importedPrivateKeyCount); } } finally { foreach (X509Certificate2 cert in collection) { cert.Dispose(); } } } [Fact] public static void X509CertificateCollectionCopyTo() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); X509Certificate[] array1 = new X509Certificate[cc.Count]; cc.CopyTo(array1, 0); Assert.Same(c1, array1[0]); Assert.Same(c2, array1[1]); Assert.Same(c3, array1[2]); X509Certificate[] array2 = new X509Certificate[cc.Count]; ((ICollection)cc).CopyTo(array2, 0); Assert.Same(c1, array2[0]); Assert.Same(c2, array2[1]); Assert.Same(c3, array2[2]); } } public static void X509ChainElementCollection_CopyTo_NonZeroLowerBound_ThrowsIndexOutOfRangeException() { using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) using (var chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot); chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags; chain.Build(microsoftDotCom); ICollection collection = chain.ChainElements; Array array = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 }); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(array, 0)); } } [Fact] public static void X509ExtensionCollection_CopyTo_NonZeroLowerBound_ThrowsIndexOutOfRangeException() { using (X509Certificate2 cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { ICollection collection = cert.Extensions; Array array = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 }); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(array, 0)); } } [Fact] public static void X509CertificateCollectionIndexOf() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2 }); Assert.Equal(0, cc.IndexOf(c1)); Assert.Equal(1, cc.IndexOf(c2)); IList il = cc; Assert.Equal(0, il.IndexOf(c1)); Assert.Equal(1, il.IndexOf(c2)); } } [Fact] public static void X509CertificateCollectionRemove() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2 }); cc.Remove(c1); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc.Remove(c2); Assert.Equal(0, cc.Count); Assert.Throws<ArgumentException>(() => cc.Remove(c2)); IList il = new X509CertificateCollection(new X509Certificate[] { c1, c2 }); il.Remove(c1); Assert.Equal(1, il.Count); Assert.Same(c2, il[0]); il.Remove(c2); Assert.Equal(0, il.Count); Assert.Throws<ArgumentException>(() => il.Remove(c2)); } } [Fact] public static void X509CertificateCollectionRemoveAt() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); cc.RemoveAt(0); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c3, cc[1]); cc.RemoveAt(1); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc.RemoveAt(0); Assert.Equal(0, cc.Count); IList il = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); il.RemoveAt(0); Assert.Equal(2, il.Count); Assert.Same(c2, il[0]); Assert.Same(c3, il[1]); il.RemoveAt(1); Assert.Equal(1, il.Count); Assert.Same(c2, il[0]); il.RemoveAt(0); Assert.Equal(0, il.Count); } } [Fact] public static void X509Certificate2CollectionRemoveRangeArray() { using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate)) using (X509Certificate2 c2 = new X509Certificate2(TestData.DssCer)) using (X509Certificate2 c1Clone = new X509Certificate2(TestData.MsCertificate)) { X509Certificate2[] array = new X509Certificate2[] { c1, c2 }; X509Certificate2Collection cc = new X509Certificate2Collection(array); cc.RemoveRange(array); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2[] { c2, c1 }); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2[] { c1 }); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc = new X509Certificate2Collection(array); Assert.Throws<ArgumentNullException>(() => cc.RemoveRange(new X509Certificate2[] { c1, c2, null })); Assert.Equal(2, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); cc = new X509Certificate2Collection(array); Assert.Throws<ArgumentNullException>(() => cc.RemoveRange(new X509Certificate2[] { c1, null, c2 })); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1, cc[1]); // Remove c1Clone (success) // Remove c1 (exception) // Add c1Clone back // End state: { c1, c2 } => { c2, c1Clone } cc = new X509Certificate2Collection(array); Assert.Throws<ArgumentException>(() => cc.RemoveRange(new X509Certificate2[] { c1Clone, c1, c2 })); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1Clone, cc[1]); } } [Fact] public static void X509Certificate2CollectionRemoveRangeCollection() { using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate)) using (X509Certificate2 c2 = new X509Certificate2(TestData.DssCer)) using (X509Certificate2 c1Clone = new X509Certificate2(TestData.MsCertificate)) using (X509Certificate c3 = new X509Certificate()) { X509Certificate2[] array = new X509Certificate2[] { c1, c2 }; X509Certificate2Collection cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2Collection { c1, c2 }); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2Collection { c2, c1 }); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2Collection { c1 }); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc = new X509Certificate2Collection(array); X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Add(c1); collection.Add(c2); ((IList)collection).Add(c3); // Add non-X509Certificate2 object Assert.Throws<InvalidCastException>(() => cc.RemoveRange(collection)); Assert.Equal(2, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); cc = new X509Certificate2Collection(array); collection = new X509Certificate2Collection(); collection.Add(c1); ((IList)collection).Add(c3); // Add non-X509Certificate2 object collection.Add(c2); Assert.Throws<InvalidCastException>(() => cc.RemoveRange(collection)); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1, cc[1]); // Remove c1Clone (success) // Remove c1 (exception) // Add c1Clone back // End state: { c1, c2 } => { c2, c1Clone } cc = new X509Certificate2Collection(array); collection = new X509Certificate2Collection { c1Clone, c1, c2, }; Assert.Throws<ArgumentException>(() => cc.RemoveRange(collection)); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1Clone, cc[1]); } } [Fact] public static void X509CertificateCollectionIndexer() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); cc[0] = c3; cc[1] = c2; cc[2] = c1; Assert.Same(c3, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c1, cc[2]); IList il = cc; il[0] = c1; il[1] = c2; il[2] = c3; Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); } } [Fact] public static void X509Certificate2CollectionIndexer() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); cc[0] = c3; cc[1] = c2; cc[2] = c1; Assert.Same(c3, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c1, cc[2]); IList il = cc; il[0] = c1; il[1] = c2; il[2] = c3; Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); } } [Fact] public static void X509CertificateCollectionInsertAndClear() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(); cc.Insert(0, c1); cc.Insert(1, c2); cc.Insert(2, c3); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); cc.Clear(); Assert.Equal(0, cc.Count); cc.Add(c1); cc.Add(c3); Assert.Equal(2, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c3, cc[1]); cc.Insert(1, c2); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); cc.Clear(); Assert.Equal(0, cc.Count); IList il = cc; il.Insert(0, c1); il.Insert(1, c2); il.Insert(2, c3); Assert.Equal(3, il.Count); Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); il.Clear(); Assert.Equal(0, il.Count); il.Add(c1); il.Add(c3); Assert.Equal(2, il.Count); Assert.Same(c1, il[0]); Assert.Same(c3, il[1]); il.Insert(1, c2); Assert.Equal(3, il.Count); Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); il.Clear(); Assert.Equal(0, il.Count); } } [Fact] public static void X509Certificate2CollectionInsert() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(); cc.Insert(0, c3); cc.Insert(0, c2); cc.Insert(0, c1); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); } } [Fact] public static void X509Certificate2CollectionCopyTo() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); X509Certificate2[] array1 = new X509Certificate2[cc.Count]; cc.CopyTo(array1, 0); Assert.Same(c1, array1[0]); Assert.Same(c2, array1[1]); Assert.Same(c3, array1[2]); X509Certificate2[] array2 = new X509Certificate2[cc.Count]; ((ICollection)cc).CopyTo(array2, 0); Assert.Same(c1, array2[0]); Assert.Same(c2, array2[1]); Assert.Same(c3, array2[2]); } } [Fact] public static void X509CertificateCollectionGetHashCode() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); int expected = c1.GetHashCode() + c2.GetHashCode() + c3.GetHashCode(); Assert.Equal(expected, cc.GetHashCode()); } } [Fact] public static void X509Certificate2CollectionGetHashCode() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); int expected = c1.GetHashCode() + c2.GetHashCode() + c3.GetHashCode(); Assert.Equal(expected, cc.GetHashCode()); } } [Fact] public static void X509ChainElementCollection_IndexerVsEnumerator() { using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) using (var chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot); chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; // Halfway between microsoftDotCom's NotBefore and NotAfter // This isn't a boundary condition test. chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; bool valid = chain.Build(microsoftDotCom); Assert.True(valid, "Precondition: Chain built validly"); int position = 0; foreach (X509ChainElement chainElement in chain.ChainElements) { X509ChainElement indexerElement = chain.ChainElements[position]; Assert.NotNull(chainElement); Assert.NotNull(indexerElement); Assert.Same(indexerElement, chainElement); position++; } } } [Fact] public static void X509ExtensionCollection_OidIndexer_ByOidValue() { const string SubjectKeyIdentifierOidValue = "2.5.29.14"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; // Stable index can be counted on by ExtensionsTests.ReadExtensions(). X509Extension skidExtension = extensions[1]; // Precondition: We've found the SKID extension. Assert.Equal(SubjectKeyIdentifierOidValue, skidExtension.Oid.Value); X509Extension byValue = extensions[SubjectKeyIdentifierOidValue]; Assert.Same(skidExtension, byValue); } } [Fact] public static void X509ExtensionCollection_OidIndexer_ByOidFriendlyName() { const string SubjectKeyIdentifierOidValue = "2.5.29.14"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; // Stable index can be counted on by ExtensionsTests.ReadExtensions(). X509Extension skidExtension = extensions[1]; // Precondition: We've found the SKID extension. Assert.Equal(SubjectKeyIdentifierOidValue, skidExtension.Oid.Value); // The friendly name of "Subject Key Identifier" is localized, but // we can use the invariant form to ask for the friendly name to ask // for the extension by friendly name. X509Extension byFriendlyName = extensions[new Oid(SubjectKeyIdentifierOidValue).FriendlyName]; Assert.Same(skidExtension, byFriendlyName); } } [Fact] public static void X509ExtensionCollection_OidIndexer_NoMatchByValue() { const string RsaOidValue = "1.2.840.113549.1.1.1"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; X509Extension byValue = extensions[RsaOidValue]; Assert.Null(byValue); } } [Fact] public static void X509ExtensionCollection_OidIndexer_NoMatchByFriendlyName() { const string RsaOidValue = "1.2.840.113549.1.1.1"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; // While "RSA" is actually invariant, this just guarantees that we're doing // the system-preferred lookup. X509Extension byFriendlyName = extensions[new Oid(RsaOidValue).FriendlyName]; Assert.Null(byFriendlyName); } } private static void TestExportSingleCert(X509ContentType ct) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { msCer, pfxCer }); byte[] blob = cc.Export(ct); Assert.Equal(ct, X509Certificate2.GetCertContentType(blob)); using (ImportedCollection ic = Cert.Import(blob)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { Assert.NotSame(msCer, c); Assert.NotSame(pfxCer, c); Assert.True(msCer.Equals(c) || pfxCer.Equals(c)); } } } } private static void TestExportStore(X509ContentType ct) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { msCer, pfxCer }); byte[] blob = cc.Export(ct); Assert.Equal(ct, X509Certificate2.GetCertContentType(blob)); using (ImportedCollection ic = Cert.Import(blob)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); using (X509Certificate2 first = cs[0]) { Assert.NotSame(msCer, first); Assert.Equal(msCer, first); } using (X509Certificate2 second = cs[1]) { Assert.NotSame(pfxCer, second); Assert.Equal(pfxCer, second); } } } } private static X509Certificate2[] ToArray(this X509Certificate2Collection col) { X509Certificate2[] array = new X509Certificate2[col.Count]; for (int i = 0; i < col.Count; i++) { array[i] = col[i]; } return array; } } }
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 museum. /// </summary> public class Museum_Core : TypeCore, ICivicStructure { public Museum_Core() { this._TypeId = 173; this._Id = "Museum"; this._Schema_Org_Url = "http://schema.org/Museum"; string label = ""; GetLabel(out label, "Museum", typeof(Museum_Core)); this._Label = label; this._Ancestors = new int[]{266,206,62}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{62}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152}; } /// <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 basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <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> /// 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> /// 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> /// 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> /// 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> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <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); } } } }
using System.Collections.Immutable; using NQuery.Symbols; using NQuery.Symbols.Aggregation; using NQuery.Syntax; using NQuery.Text; namespace NQuery.Binding { partial class Binder { private void EnsureCaseLabelsEvaluateToBool(ImmutableArray<CaseLabelSyntax> caseLabels, ImmutableArray<BoundCaseLabel> boundCaseLabels) { for (var i = 0; i < caseLabels.Length; i++) { var type = boundCaseLabels[i].Condition.Type; if (!type.IsError() && type != typeof(bool)) Diagnostics.ReportWhenMustEvaluateToBool(caseLabels[i].WhenExpression.Span); } } private static Type FindCommonType(ImmutableArray<BoundExpression> boundExpressions) { // The common type C among a type set T1..TN is defined as follows: // // (1) C has to be in the set T1..TN. In other words we don't consider // types not already present. // // (2) All types T1..T2 have to have an identity conversion or an implicit // conversion to C. // // (3) C has to be the only type for which (1) and (2) hold. Type commonType = null; foreach (var target in boundExpressions) { if (target.Type.IsError() || target.Type == commonType) continue; var allOthersCanConvertToTarget = true; foreach (var source in boundExpressions) { if (source.Type.IsError() || source.Type == target.Type) continue; var conversion = Conversion.Classify(source.Type, target.Type); if (!conversion.IsImplicit) { allOthersCanConvertToTarget = false; break; } } if (allOthersCanConvertToTarget) { if (commonType is null) { commonType = target.Type; } else { // TODO: We may want to report an ambiguity error here. commonType = null; break; } } } return commonType; } private Type BindType(SyntaxToken typeName) { var type = LookupType(typeName); if (type is not null) return type; Diagnostics.ReportUndeclaredType(typeName); return TypeFacts.Unknown; } private static BoundExpression BindArgument<T>(BoundExpression expression, OverloadResolutionResult<T> result, int argumentIndex) where T : Signature { var selected = result.Selected; if (selected is null) return expression; var targetType = selected.Signature.GetParameterType(argumentIndex); var conversion = selected.ArgumentConversions[argumentIndex]; // TODO: We need check for ambiguous conversions here as well. return conversion.IsIdentity ? expression : new BoundConversionExpression(expression, targetType, conversion); } private ImmutableArray<BoundExpression> BindToCommonType(IReadOnlyList<ExpressionSyntax> expressions) { var boundExpressions = expressions.Select(BindExpression).ToImmutableArray(); return BindToCommonType(boundExpressions, i => expressions[i].Span); } private ImmutableArray<BoundExpression> BindToCommonType(ImmutableArray<BoundExpression> boundExpressions, TextSpan diagnosticSpan) { return BindToCommonType(boundExpressions, _ => diagnosticSpan); } private ImmutableArray<BoundExpression> BindToCommonType(ImmutableArray<BoundExpression> boundExpressions, Func<int, TextSpan> diagnosticSpanProvider) { // To avoid cascading errors let's first see whether we couldn't resolve // any of the expressions. If that's the case, we'll simply return them as-is. var hasAnyErrors = boundExpressions.Any(e => e.Type.IsError()); if (hasAnyErrors) return boundExpressions; // Now let's see whether all expressions already have the same type. // In that case we can simply return the input as-is. var firstType = boundExpressions.Select(e => e.Type).First(); var allAreSameType = boundExpressions.All(e => e.Type == firstType); if (allAreSameType) return boundExpressions; // Not all expressions have the same type. Let's try to find a common type. var commonType = FindCommonType(boundExpressions); // If we couldn't find a common type, we'll just use the first expression's // type -- this will cause BindConversion below to report errors. if (commonType is null) commonType = boundExpressions.First().Type; return boundExpressions.Select((e, i) => BindConversion(diagnosticSpanProvider(i), e, commonType)).ToImmutableArray(); } private void BindToCommonType(TextSpan diagnosticSpan, ValueSlot left, ValueSlot right, out BoundExpression newLeft, out BoundExpression newRight) { newLeft = null; newRight = null; if (left.Type == right.Type || left.Type.IsError() || right.Type.IsError()) return; var conversionLeftToRight = Conversion.Classify(left.Type, right.Type); var conversionRightToLeft = Conversion.Classify(right.Type, left.Type); if (conversionLeftToRight.IsImplicit && conversionRightToLeft.IsImplicit) { // TODO: We may want to report an ambiguity error here. } if (conversionLeftToRight.IsImplicit) { newLeft = BindConversion(diagnosticSpan, new BoundValueSlotExpression(left), right.Type); } else { newRight = BindConversion(diagnosticSpan, new BoundValueSlotExpression(right), left.Type); } } private BoundExpression BindConversion(TextSpan diagnosticSpan, BoundExpression expression, Type targetType) { var sourceType = expression.Type; var conversion = Conversion.Classify(sourceType, targetType); if (conversion.IsIdentity) return expression; // To avoid cascading errors, we'll only validate the result // if we could resolve both, the expression as well as the // target type. if (!sourceType.IsError() && !targetType.IsError()) { if (!conversion.Exists) Diagnostics.ReportCannotConvert(diagnosticSpan, sourceType, targetType); else if (conversion.ConversionMethods.Length > 1) Diagnostics.ReportAmbiguousConversion(diagnosticSpan, sourceType, targetType); } return new BoundConversionExpression(expression, targetType, conversion); } private BoundExpression BindExpression(ExpressionSyntax node) { var result = Bind(node, BindExpressionInternal); // If we've already allocated a value slot for the given expression, // we want our caller to refer to this value slot. if (TryReplaceExpression(node, result, out var valueSlot)) return new BoundValueSlotExpression(valueSlot); return result; } private BoundExpression BindExpressionInternal(ExpressionSyntax node) { switch (node.Kind) { case SyntaxKind.ComplementExpression: case SyntaxKind.IdentityExpression: case SyntaxKind.NegationExpression: case SyntaxKind.LogicalNotExpression: return BindUnaryExpression((UnaryExpressionSyntax)node); case SyntaxKind.BitwiseAndExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.AddExpression: case SyntaxKind.SubExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.PowerExpression: case SyntaxKind.EqualExpression: case SyntaxKind.NotEqualExpression: case SyntaxKind.LessExpression: case SyntaxKind.LessOrEqualExpression: case SyntaxKind.GreaterExpression: case SyntaxKind.GreaterOrEqualExpression: case SyntaxKind.NotLessExpression: case SyntaxKind.NotGreaterExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: case SyntaxKind.LogicalAndExpression: case SyntaxKind.LogicalOrExpression: return BindBinaryExpression((BinaryExpressionSyntax)node); case SyntaxKind.LikeExpression: return BindLikeExpression((LikeExpressionSyntax)node); case SyntaxKind.SoundsLikeExpression: return BindSoundsLikeExpression((SoundsLikeExpressionSyntax)node); case SyntaxKind.SimilarToExpression: return BindSimilarToExpression((SimilarToExpressionSyntax)node); case SyntaxKind.ParenthesizedExpression: return BindParenthesizedExpression((ParenthesizedExpressionSyntax)node); case SyntaxKind.BetweenExpression: return BindBetweenExpression((BetweenExpressionSyntax)node); case SyntaxKind.IsNullExpression: return BindIsNullExpression((IsNullExpressionSyntax)node); case SyntaxKind.CastExpression: return BindCastExpression((CastExpressionSyntax)node); case SyntaxKind.CaseExpression: return BindCaseExpression((CaseExpressionSyntax)node); case SyntaxKind.CoalesceExpression: return BindCoalesceExpression((CoalesceExpressionSyntax)node); case SyntaxKind.NullIfExpression: return BindNullIfExpression((NullIfExpressionSyntax)node); case SyntaxKind.InExpression: return BindInExpression((InExpressionSyntax)node); case SyntaxKind.InQueryExpression: return BindInQueryExpression((InQueryExpressionSyntax)node); case SyntaxKind.LiteralExpression: return BindLiteralExpression((LiteralExpressionSyntax)node); case SyntaxKind.VariableExpression: return BindVariableExpression((VariableExpressionSyntax)node); case SyntaxKind.NameExpression: return BindNameExpression((NameExpressionSyntax)node); case SyntaxKind.PropertyAccessExpression: return BindPropertyAccessExpression((PropertyAccessExpressionSyntax)node); case SyntaxKind.CountAllExpression: return BindCountAllExpression((CountAllExpressionSyntax)node); case SyntaxKind.FunctionInvocationExpression: return BindFunctionInvocationExpression((FunctionInvocationExpressionSyntax)node); case SyntaxKind.MethodInvocationExpression: return BindMethodInvocationExpression((MethodInvocationExpressionSyntax)node); case SyntaxKind.SingleRowSubselect: return BindSingleRowSubselect((SingleRowSubselectSyntax)node); case SyntaxKind.ExistsSubselect: return BindExistsSubselect((ExistsSubselectSyntax)node); case SyntaxKind.AllAnySubselect: return BindAllAnySubselect((AllAnySubselectSyntax)node); default: throw ExceptionBuilder.UnexpectedValue(node.Kind); } } private BoundExpression BindUnaryExpression(UnaryExpressionSyntax node) { var operatorKind = node.Kind.ToUnaryOperatorKind(); return BindUnaryExpression(node.Span, operatorKind, node.Expression); } private BoundExpression BindUnaryExpression(TextSpan diagnosticSpan, UnaryOperatorKind operatorKind, ExpressionSyntax expression) { var boundExpression = BindExpression(expression); return BindUnaryExpression(diagnosticSpan, operatorKind, boundExpression); } private BoundExpression BindUnaryExpression(TextSpan diagnosticSpan, UnaryOperatorKind operatorKind, BoundExpression expression) { // To avoid cascading errors, we'll return a unary expression that isn't bound to // an operator if the expression couldn't be resolved. if (expression.Type.IsError()) return new BoundUnaryExpression(operatorKind, OverloadResolutionResult<UnaryOperatorSignature>.None, expression); var result = LookupUnaryOperator(operatorKind, expression); if (result.Best is null) { if (result.Selected is null) { Diagnostics.ReportCannotApplyUnaryOperator(diagnosticSpan, operatorKind, expression.Type); } else { Diagnostics.ReportAmbiguousUnaryOperator(diagnosticSpan, operatorKind, expression.Type); } } // Convert argument (if necessary) var convertedArgument = BindArgument(expression, result, 0); return new BoundUnaryExpression(operatorKind, result, convertedArgument); } private BoundExpression BindOptionalNegation(TextSpan diagnosticSpan, SyntaxToken notKeyword, BoundExpression expression) { return notKeyword is null ? expression : BindUnaryExpression(diagnosticSpan, UnaryOperatorKind.LogicalNot, expression); } private BoundExpression BindBinaryExpression(BinaryExpressionSyntax node) { var operatorKind = node.Kind.ToBinaryOperatorKind(); return BindBinaryExpression(node.Span, operatorKind, node.Left, node.Right); } private BoundExpression BindBinaryExpression(TextSpan diagnosticSpan, BinaryOperatorKind operatorKind, ExpressionSyntax left, ExpressionSyntax right) { var boundLeft = BindExpression(left); var boundRight = BindExpression(right); return BindBinaryExpression(diagnosticSpan, operatorKind, boundLeft, boundRight); } private BoundExpression BindBinaryExpression(TextSpan diagnosticSpan, BinaryOperatorKind operatorKind, BoundExpression left, BoundExpression right) { // In order to avoid cascading errors, we'll return a binary expression without an operator // if either side couldn't be resolved. if (left.Type.IsError() || right.Type.IsError()) return new BoundBinaryExpression(left, operatorKind, OverloadResolutionResult<BinaryOperatorSignature>.None, right); // TODO: We should consider supporting three-state-short-circuit evaluation. // // TODO: C# doesn't allow overloading && or ||. Instead, you need to overload & and | *and* you need to define operator true/operator false: // // The operation x && y is evaluated as T.false(x) ? x : T.&(x, y) // The operation x || y is evaluated as T.true(x) ? x : T.|(x, y) var result = LookupBinaryOperator(operatorKind, left, right); if (result.Best is null) { if (result.Selected is null) { Diagnostics.ReportCannotApplyBinaryOperator(diagnosticSpan, operatorKind, left.Type, right.Type); } else { Diagnostics.ReportAmbiguousBinaryOperator(diagnosticSpan, operatorKind, left.Type, right.Type); } } // Convert arguments (if necessary) var convertedLeft = BindArgument(left, result, 0); var convertedRight = BindArgument(right, result, 1); return new BoundBinaryExpression(convertedLeft, operatorKind, result, convertedRight); } private BoundExpression BindBinaryExpression(TextSpan diagnosticSpan, SyntaxToken notKeyword, BinaryOperatorKind operatorKind, ExpressionSyntax left, ExpressionSyntax right) { var expression = BindBinaryExpression(diagnosticSpan, operatorKind, left, right); return BindOptionalNegation(diagnosticSpan, notKeyword, expression); } private BoundExpression BindLikeExpression(LikeExpressionSyntax node) { return BindBinaryExpression(node.Span, node.NotKeyword, BinaryOperatorKind.Like, node.Left, node.Right); } private BoundExpression BindSoundsLikeExpression(SoundsLikeExpressionSyntax node) { return BindBinaryExpression(node.Span, node.NotKeyword, BinaryOperatorKind.SoundsLike, node.Left, node.Right); } private BoundExpression BindSimilarToExpression(SimilarToExpressionSyntax node) { return BindBinaryExpression(node.Span, node.NotKeyword, BinaryOperatorKind.SimilarTo, node.Left, node.Right); } private BoundExpression BindParenthesizedExpression(ParenthesizedExpressionSyntax node) { return BindExpression(node.Expression); } private BoundExpression BindBetweenExpression(BetweenExpressionSyntax node) { // left BETWEEN lowerBound AND upperBound // // ===> // // left >= lowerBound AND left <= upperBound var left = BindExpression(node.Left); var lowerBound = BindExpression(node.LowerBound); var upperBound = BindExpression(node.UpperBound); var lowerCheck = BindBinaryExpression(node.Span, BinaryOperatorKind.GreaterOrEqual, left, lowerBound); var upperCheck = BindBinaryExpression(node.Span, BinaryOperatorKind.LessOrEqual, left, upperBound); var boundsCheck = BindBinaryExpression(node.Span, BinaryOperatorKind.LogicalAnd, lowerCheck, upperCheck); return BindOptionalNegation(node.Span, node.NotKeyword, boundsCheck); } private BoundExpression BindIsNullExpression(IsNullExpressionSyntax node) { var expression = BindExpression(node.Expression); var isNull = new BoundIsNullExpression(expression); return BindOptionalNegation(node.Span, node.NotKeyword, isNull); } private BoundExpression BindCastExpression(CastExpressionSyntax node) { var expression = BindExpression(node.Expression); var targetType = BindType(node.TypeName); return BindConversion(node.Span, expression, targetType); } private BoundExpression BindCaseExpression(CaseExpressionSyntax node) { return node.InputExpression is null ? BindRegularCase(node) : BindSearchedCase(node); } private BoundExpression BindRegularCase(CaseExpressionSyntax node) { // CASE // WHEN e1 THEN r1 // WHEN e2 THEN r2 // ... // ELSE re // END CASE var boundResults = BindCaseResultExpressions(node); var boundCaseLabels = node.CaseLabels.Select((l, i) => new BoundCaseLabel(BindExpression(l.WhenExpression), boundResults[i])).ToImmutableArray(); var boundElse = node.ElseLabel is null ? null : boundResults.Last(); EnsureCaseLabelsEvaluateToBool(node.CaseLabels, boundCaseLabels); return new BoundCaseExpression(boundCaseLabels, boundElse); } private BoundExpression BindSearchedCase(CaseExpressionSyntax node) { // CASE x // WHEN e1 THEN r1 // WHEN e2 THEN r2 // ... // ELSE re // END CASE // // ==> // // CASE // WHEN x = e1 THEN r1 // WHEN x = e2 THEN r2 // ... // ELSE re // END CASE var boundInput = BindExpression(node.InputExpression); var boundResults = BindCaseResultExpressions(node); var boundCaseLabels = (from t in node.CaseLabels.Select((c, i) => (CaseLabel: c, Index: i)) let caseLabel = t.CaseLabel let i = t.Index let boundWhen = BindExpression(caseLabel.WhenExpression) let boundCondition = BindBinaryExpression(caseLabel.WhenExpression.Span, BinaryOperatorKind.Equal, boundInput, boundWhen) let boundThen = boundResults[i] select new BoundCaseLabel(boundCondition, boundThen)).ToImmutableArray(); var boundElse = node.ElseLabel is null ? null : boundResults.Last(); EnsureCaseLabelsEvaluateToBool(node.CaseLabels, boundCaseLabels); return new BoundCaseExpression(boundCaseLabels, boundElse); } private ImmutableArray<BoundExpression> BindCaseResultExpressions(CaseExpressionSyntax node) { var elseExpression = node.ElseLabel is null ? Enumerable.Empty<ExpressionSyntax>() : new[] { node.ElseLabel.Expression }; var expressions = node.CaseLabels.Select(l => l.ThenExpression).Concat(elseExpression).ToImmutableArray(); return BindToCommonType(expressions); } private BoundExpression BindCoalesceExpression(CoalesceExpressionSyntax node) { // COALESCE(e1, e2, .. eN) // // ====> // // CASE // WHEN e1 IS NOT NULL THEN e1 // .. // WHEN e2 IS NOT NULL THEN e2 // ELSE // eN // END var boundArguments = BindToCommonType(node.ArgumentList.Arguments); var caseLabelCount = node.ArgumentList.Arguments.Count - 1; var caseLabels = new BoundCaseLabel[caseLabelCount]; for (var i = 0; i < caseLabelCount; i++) { var argument = node.ArgumentList.Arguments[i]; var boundArgument = boundArguments[i]; var boundIsNullExpression = new BoundIsNullExpression(boundArgument); var boundIsNullNegation = BindUnaryExpression(argument.Span, UnaryOperatorKind.LogicalNot, boundIsNullExpression); var caseLabel = new BoundCaseLabel(boundIsNullNegation, boundArgument); caseLabels[i] = caseLabel; } var elseExpression = boundArguments.Last(); return new BoundCaseExpression(caseLabels, elseExpression); } private BoundExpression BindNullIfExpression(NullIfExpressionSyntax node) { // NULLIF(left, right) // // ===> // // CASE WHEN left != right THEN left END var expressions = BindToCommonType(new[] { node.LeftExpression, node.RightExpression }); var boundLeft = expressions[0]; var boundRight = expressions[1]; var boundComparison = BindBinaryExpression(node.Span, BinaryOperatorKind.NotEqual, boundLeft, boundRight); var boundCaseLabel = new BoundCaseLabel(boundComparison, boundLeft); return new BoundCaseExpression(new[] { boundCaseLabel }, null); } private BoundExpression BindInExpression(InExpressionSyntax node) { // e IN (e1, e2..eN) // // ===> // // e = e1 OR e = e2 .. OR e = eN var boundExpression = BindExpression(node.Expression); var boundComparisons = from a in node.ArgumentList.Arguments let boundArgument = BindExpression(a) let boundComparision = BindBinaryExpression(a.Span, BinaryOperatorKind.Equal, boundExpression, boundArgument) select boundComparision; var inExpressionsAggregate = boundComparisons.Aggregate<BoundExpression, BoundExpression>(null, (c, b) => c is null ? b : BindBinaryExpression(node.Span, BinaryOperatorKind.LogicalOr, c, b)); return BindOptionalNegation(node.Span, node.NotKeyword, inExpressionsAggregate); } private BoundExpression BindInQueryExpression(InQueryExpressionSyntax node) { // NOTE: It's tempting to bind this using BindAllAnySubselect and // BindOptionalNegation. However, that's not resulting in the // correct predicate as negated IN expressions have to handle // NULL values differently. We can, however, lower NOT IN using // != ALL, which will do exactly that. if (node.NotKeyword is null) { // left IN (SELECT right FROM ...) // // ==> // // left = ANY (SELECT right FROM ...) return BindAllAnySubselect(node.Span, node.Expression, false, node.Query, BinaryOperatorKind.Equal); } else { // left NOT IN (SELECT right FROM ...) // // ==> // // left != ALL (SELECT right FROM ...) return BindAllAnySubselect(node.Span, node.Expression, true, node.Query, BinaryOperatorKind.NotEqual); } } private static BoundExpression BindLiteralExpression(LiteralExpressionSyntax node) { return new BoundLiteralExpression(node.Value); } private BoundExpression BindVariableExpression(VariableExpressionSyntax node) { var symbols = LookupVariable(node.Name).ToImmutableArray(); if (symbols.Length == 0) { Diagnostics.ReportUndeclaredVariable(node); return new BoundErrorExpression(); } if (symbols.Length > 1) Diagnostics.ReportAmbiguousVariable(node.Name); var variableSymbol = symbols[0]; return new BoundVariableExpression(variableSymbol); } private BoundExpression BindNameExpression(NameExpressionSyntax node) { if (node.Name.IsMissing) { // If this token was inserted by the parser, there is no point in // trying to resolve this guy. return new BoundErrorExpression(); } var name = node.Name; var symbols = LookupColumnTableOrVariable(name).ToImmutableArray(); if (symbols.Length == 0) { var isInvocable = LookupSymbols<FunctionSymbol>(name).Any() || LookupSymbols<AggregateSymbol>(name).Any(); if (isInvocable) Diagnostics.ReportInvocationRequiresParenthesis(name); else Diagnostics.ReportColumnTableOrVariableNotDeclared(name); return new BoundErrorExpression(); } if (symbols.Length > 1) Diagnostics.ReportAmbiguousName(name, symbols); var symbol = symbols.First(); switch (symbol.Kind) { case SymbolKind.TableColumnInstance: return new BoundColumnExpression((ColumnInstanceSymbol)symbol); case SymbolKind.Variable: return new BoundVariableExpression((VariableSymbol)symbol); case SymbolKind.TableInstance: { // If symbol refers to a table, we need to make sure that it's either not a derived table/CTE // or we are used in column access context (i.e. our parent is a property access). // // For example, the following query is invalid: // // SELECT D -- ERROR // FROM ( // SELECT * // FROM Employees e // ) AS D // // You cannot obtain a value for D itself. var tableInstance = symbol as TableInstanceSymbol; if (tableInstance is not null) { // TODO: Fully support row access //var isColumnAccess = node.Parent is PropertyAccessExpressionSyntax; //var hasNoType = tableInstance.Table.Type.IsMissing(); //if (!isColumnAccess && hasNoType) // Diagnostics.ReportInvalidRowReference(name); var isColumnAccess = node.Parent is PropertyAccessExpressionSyntax; if (!isColumnAccess) { Diagnostics.ReportInvalidRowReference(name); return new BoundErrorExpression(); } } return new BoundTableExpression(tableInstance); } default: throw ExceptionBuilder.UnexpectedValue(symbol.Kind); } } private BoundExpression BindPropertyAccessExpression(PropertyAccessExpressionSyntax node) { var target = BindExpression(node.Target); // For cases like Foo.Bar we check whether 'Foo' was resolved to a table instance. // If that's the case we bind a column otherwise we bind a normal expression. if (target is BoundTableExpression boundTable) { // In Foo.Bar, Foo was resolved to a table. Bind Bar as column. var tableInstance = boundTable.Symbol; return BindColumnInstance(node, tableInstance); } // node.Target either wasn't a name expression or didn't resolve to a // table instance. Resolve node.Name as a property. var name = node.Name; if (target.Type.IsError()) { // To avoid cascading errors, we'll give up early. return new BoundErrorExpression(); } var propertySymbols = LookupProperty(target.Type, name).ToImmutableArray(); if (propertySymbols.Length == 0) { var hasMethods = LookupMethod(target.Type, name).Any(); if (hasMethods) Diagnostics.ReportInvocationRequiresParenthesis(name); else Diagnostics.ReportUndeclaredProperty(node, target.Type); return new BoundErrorExpression(); } if (propertySymbols.Length > 1) Diagnostics.ReportAmbiguousProperty(name); var propertySymbol = propertySymbols[0]; return new BoundPropertyAccessExpression(target, propertySymbol); } private BoundExpression BindColumnInstance(PropertyAccessExpressionSyntax node, TableInstanceSymbol tableInstance) { var columnName = node.Name; var columnInstances = tableInstance.ColumnInstances.Where(c => columnName.Matches(c.Name)).ToImmutableArray(); if (columnInstances.Length == 0) { Diagnostics.ReportUndeclaredColumn(node, tableInstance); return new BoundErrorExpression(); } if (columnInstances.Length > 1) Diagnostics.ReportAmbiguousColumnInstance(columnName, columnInstances); var columnInstance = columnInstances.First(); return new BoundColumnExpression(columnInstance); } private BoundExpression BindCountAllExpression(CountAllExpressionSyntax node) { var aggregates = LookupAggregate(node.Name).ToImmutableArray(); if (aggregates.Length == 0) { Diagnostics.ReportUndeclaredAggregate(node.Name); return new BoundErrorExpression(); } if (aggregates.Length > 1) Diagnostics.ReportAmbiguousAggregate(node.Name, aggregates); var aggregate = aggregates[0]; var boundArgument = new BoundLiteralExpression(0); var boundAggregatable = BindAggregatable(node.Span, aggregate, boundArgument); var boundAggregate = new BoundAggregateExpression(aggregate, boundAggregatable, boundArgument); return BindAggregate(node, boundAggregate); } private BoundExpression BindFunctionInvocationExpression(FunctionInvocationExpressionSyntax node) { if (node.ArgumentList.Arguments.Count == 1) { // Could be an aggregate or a function. var aggregates = LookupAggregate(node.Name).ToImmutableArray(); var functionCandidate = LookupFunctionWithSingleParameter(node.Name).FirstOrDefault(); if (aggregates.Length > 0) { if (functionCandidate is not null) { var symbols = new Symbol[] { aggregates[0], functionCandidate }; Diagnostics.ReportAmbiguousName(node.Name, symbols); } else { if (aggregates.Length > 1) Diagnostics.ReportAmbiguousAggregate(node.Name, aggregates); var aggregate = aggregates[0]; return BindAggregateInvocationExpression(node, aggregate); } } } var name = node.Name; var arguments = node.ArgumentList.Arguments.Select(BindExpression).ToImmutableArray(); var argumentTypes = arguments.Select(a => a.Type).ToImmutableArray(); // To avoid cascading errors, we'll return a node that isn't bound to any function // if we couldn't resolve any of our arguments. var anyErrorsInArguments = argumentTypes.Any(a => a.IsError()); if (anyErrorsInArguments) return new BoundFunctionInvocationExpression(arguments, OverloadResolutionResult<FunctionSymbolSignature>.None); var result = LookupFunction(name, argumentTypes); if (result.Best is null) { if (result.Selected is null) { Diagnostics.ReportUndeclaredFunction(node, argumentTypes); return new BoundErrorExpression(); } var symbol1 = result.Selected.Signature.Symbol; var symbol2 = result.Candidates.First(c => c.IsSuitable && c.Signature.Symbol != symbol1).Signature.Symbol; Diagnostics.ReportAmbiguousInvocation(node.Span, symbol1, symbol2, argumentTypes); } // Convert all arguments (if necessary) var convertedArguments = arguments.Select((a, i) => BindArgument(a, result, i)).ToImmutableArray(); return new BoundFunctionInvocationExpression(convertedArguments, result); } private BoundExpression BindAggregateInvocationExpression(FunctionInvocationExpressionSyntax node, AggregateSymbol aggregate) { var argument = node.ArgumentList.Arguments[0]; var argumentBinder = CreateAggregateArgumentBinder(); var boundArgument = argumentBinder.BindExpression(argument); var boundAggregatable = BindAggregatable(node.Span, aggregate, boundArgument); var boundAggregate = new BoundAggregateExpression(aggregate, boundAggregatable, boundArgument); return BindAggregate(node, boundAggregate); } private IAggregatable BindAggregatable(TextSpan errorSpan, AggregateSymbol aggregate, BoundExpression boundArgument) { var aggregatable = boundArgument.Type.IsError() ? null : aggregate.Definition.CreateAggregatable(boundArgument.Type); if (!boundArgument.Type.IsError() && aggregatable is null) Diagnostics.ReportAggregateDoesNotSupportType(errorSpan, aggregate, boundArgument.Type); return aggregatable; } private BoundExpression BindAggregate(ExpressionSyntax aggregate, BoundAggregateExpression boundAggregate) { var affectedQueryScopes = aggregate.DescendantNodes() .Select(GetBoundNode<BoundColumnExpression>) .Where(n => n is not null) .Select(b => b.Symbol) .OfType<TableColumnInstanceSymbol>() .Select(c => FindQueryState(c.TableInstance)) .Distinct() .Take(2) .ToImmutableArray(); if (affectedQueryScopes.Length > 1) Diagnostics.ReportAggregateContainsColumnsFromDifferentQueries(aggregate.Span); var queryState = affectedQueryScopes.DefaultIfEmpty(QueryState) .First(); if (queryState is null) { Diagnostics.ReportAggregateInvalidInCurrentContext(aggregate.Span); } else { var existingSlot = FindComputedValue(aggregate, queryState.ComputedAggregates); if (existingSlot is null) { var slot = ValueSlotFactory.CreateTemporary(boundAggregate.Type); queryState.ComputedAggregates.Add(new BoundComputedValueWithSyntax(aggregate, boundAggregate, slot)); } } var aggregateBelongsToCurrentQuery = QueryState == queryState; if (InOnClause && aggregateBelongsToCurrentQuery) { Diagnostics.ReportAggregateInOn(aggregate.Span); } else if (InWhereClause && aggregateBelongsToCurrentQuery) { Diagnostics.ReportAggregateInWhere(aggregate.Span); } else if (InGroupByClause && aggregateBelongsToCurrentQuery) { Diagnostics.ReportAggregateInGroupBy(aggregate.Span); } else if (InAggregateArgument) { Diagnostics.ReportAggregateInAggregateArgument(aggregate.Span); } return boundAggregate; } private BoundExpression BindMethodInvocationExpression(MethodInvocationExpressionSyntax node) { var target = BindExpression(node.Target); var name = node.Name; var arguments = node.ArgumentList.Arguments.Select(BindExpression).ToImmutableArray(); var argumentTypes = arguments.Select(a => a.Type).ToImmutableArray(); // To avoid cascading errors, we'll return a node that isn't bound to // any method if we couldn't resolve our target or any of our arguments. var anyErrors = target.Type.IsError() || argumentTypes.Any(a => a.IsError()); if (anyErrors) return new BoundMethodInvocationExpression(target, arguments, OverloadResolutionResult<MethodSymbolSignature>.None); var result = LookupMethod(target.Type, name, argumentTypes); if (result.Best is null) { if (result.Selected is null) { Diagnostics.ReportUndeclaredMethod(node, target.Type, argumentTypes); return new BoundErrorExpression(); } var symbol1 = result.Selected.Signature.Symbol; var symbol2 = result.Candidates.First(c => c.IsSuitable && c.Signature.Symbol != symbol1).Signature.Symbol; Diagnostics.ReportAmbiguousInvocation(node.Span, symbol1, symbol2, argumentTypes); } // Convert all arguments (if necessary) var convertedArguments = arguments.Select((a, i) => BindArgument(a, result, i)).ToImmutableArray(); return new BoundMethodInvocationExpression(target, convertedArguments, result); } private BoundExpression BindSingleRowSubselect(SingleRowSubselectSyntax node) { // TODO: Ensure query has no ORDER BY unless TOP is also specified var boundQuery = BindSubquery(node.Query); if (boundQuery.OutputColumns.Length == 0) { // This can happen in cases like this: // // SELECT (SELECT * FROM // FROM EmployeeTerritories et // // We shouldn't report an error but we can't return bound // single row subselect either. return new BoundErrorExpression(); } if (boundQuery.OutputColumns.Length > 1) Diagnostics.ReportTooManyExpressionsInSelectListOfSubquery(node.Span); var value = boundQuery.OutputColumns.First().ValueSlot; return new BoundSingleRowSubselect(value, boundQuery.Relation); } private BoundExpression BindExistsSubselect(ExistsSubselectSyntax node) { // TODO: Ensure query has no ORDER BY unless TOP is also specified var boundQuery = BindSubquery(node.Query); // NOTE: Number of columns doesn't matter here return new BoundExistsSubselect(boundQuery.Relation); } private BoundExpression BindAllAnySubselect(AllAnySubselectSyntax node) { var expressionKind = SyntaxFacts.GetBinaryOperatorExpression(node.OperatorToken.Kind); var operatorKind = expressionKind.ToBinaryOperatorKind(); var isAll = node.Keyword.Kind == SyntaxKind.AllKeyword; return BindAllAnySubselect(node.Span, node.Left, isAll, node.Query, operatorKind); } private BoundExpression BindAllAnySubselect(TextSpan diagnosticSpan, ExpressionSyntax leftNode, bool isAll, QuerySyntax queryNode, BinaryOperatorKind operatorKind) { // TODO: Ensure query has no ORDER BY unless TOP is also specified // First, let's bind the expression and the query var left = BindExpression(leftNode); var boundQuery = BindSubquery(queryNode); // The right hand side of the binary expression is the first column of the query. if (boundQuery.OutputColumns.Length == 0) { var outputValue = ValueSlotFactory.CreateTemporary(typeof(bool)); return new BoundValueSlotExpression(outputValue); } if (boundQuery.OutputColumns.Length > 1) Diagnostics.ReportTooManyExpressionsInSelectListOfSubquery(queryNode.Span); var rightColumn = boundQuery.OutputColumns[0]; var right = new BoundValueSlotExpression(rightColumn.ValueSlot); // Now we need to bind the binary operator. // // To avoid cascading errors, we'll only validate the operator // if we could resolve both sides. if (left.Type.IsError() || right.Type.IsError()) return new BoundErrorExpression(); var result = LookupBinaryOperator(operatorKind, left.Type, right.Type); if (result.Best is null) { if (result.Selected is null) Diagnostics.ReportCannotApplyBinaryOperator(diagnosticSpan, operatorKind, left.Type, right.Type); else Diagnostics.ReportAmbiguousBinaryOperator(diagnosticSpan, operatorKind, left.Type, right.Type); } // We may need to convert the arguments to the binary operator, so let's // bind them as arguments to the resolved operator. var convertedLeft = BindArgument(left, result, 0); var convertedRight = BindArgument(right, result, 1); // If we need to convert the right side, then we must insert a BoundComputeRelation // that produces a derived value. BoundRelation relation; if (convertedRight == right) { relation = boundQuery.Relation; } else { var outputValue = ValueSlotFactory.CreateTemporary(convertedRight.Type); var outputValues = new[] { outputValue }; var computedValue = new BoundComputedValue(convertedRight, outputValue); var computedValues = new[] { computedValue }; var computeRelation = new BoundComputeRelation(boundQuery.Relation, computedValues); relation = new BoundProjectRelation(computeRelation, outputValues); convertedRight = new BoundValueSlotExpression(outputValue); } // In order to simplify later phases, we'll rewrite the ALL/ANY subselect into // a regular EXISTS subselect. ANY is fairly straightforward: // // left op ANY (SELECT right FROM ...) // // ===> // // EXISTS (SELECT * FROM ... WHERE left op right) // // ALL requires a bit more trickery as we need to handle NULL values in the negated // predicate correctly: // // left op ALL (SELECT Column FROM ...) // // ===> // // NOT EXISTS (SELECT * FROM ... WHERE NOT (left op right) OR (left IS NULL) OR (right IS NULL)) if (!isAll) { var condition = new BoundBinaryExpression(convertedLeft, operatorKind, result, convertedRight); var filter = new BoundFilterRelation(relation, condition); return new BoundExistsSubselect(filter); } else { var comparison = new BoundBinaryExpression(convertedLeft, operatorKind, result, right); var negatedComparison = BindUnaryExpression(diagnosticSpan, UnaryOperatorKind.LogicalNot, comparison); var leftIsNull = new BoundIsNullExpression(convertedLeft); var rightIsNull = new BoundIsNullExpression(right); var eitherSideIsNull = BindBinaryExpression(diagnosticSpan, BinaryOperatorKind.LogicalOr, leftIsNull, rightIsNull); var condition = BindBinaryExpression(diagnosticSpan, BinaryOperatorKind.LogicalOr, negatedComparison, eitherSideIsNull); var filter = new BoundFilterRelation(relation, condition); var existsSubselect = new BoundExistsSubselect(filter); return BindUnaryExpression(diagnosticSpan, UnaryOperatorKind.LogicalNot, existsSubselect); } } } }
// // Copyright (c) @jevertt // Copyright (c) Rafael Rivera // Licensed under the MIT License. See LICENSE in the project root for license information. // using System.IO; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; using System.Net; using System; using System.Xml; namespace SpectatorView { /// <summary> /// Build window - supports SLN creation, APPX from SLN, Deploy on device, and misc helper utilities associated with the build/deploy/test iteration loop /// Requires the device to be set in developer mode & to have secure connections disabled (in the security tab in the device portal) /// </summary> public class BuildDeployWindow : EditorWindow { private const float GUISectionOffset = 10.0f; private const string GUIHorizSpacer = " "; private const float UpdateBuildsPeriod = 1.0f; // Properties private bool ShouldOpenSLNBeEnabled { get { return !string.IsNullOrEmpty(BuildDeployPrefs.BuildDirectory); } } private bool ShouldBuildSLNBeEnabled { get { return !string.IsNullOrEmpty(BuildDeployPrefs.BuildDirectory); } } private bool ShouldBuildAppxBeEnabled { get { return !string.IsNullOrEmpty(BuildDeployPrefs.BuildDirectory) && !string.IsNullOrEmpty(BuildDeployPrefs.MsBuildVersion) && !string.IsNullOrEmpty(BuildDeployPrefs.BuildConfig); } } private bool ShouldLaunchAppBeEnabled { get { return !string.IsNullOrEmpty(BuildDeployPrefs.TargetIPs) && !string.IsNullOrEmpty(BuildDeployPrefs.BuildDirectory); } } private bool ShouldWebPortalBeEnabled { get { return !string.IsNullOrEmpty(BuildDeployPrefs.TargetIPs) && !string.IsNullOrEmpty(BuildDeployPrefs.BuildDirectory); } } private bool ShouldLogViewBeEnabled { get { return !string.IsNullOrEmpty(BuildDeployPrefs.TargetIPs) && !string.IsNullOrEmpty(BuildDeployPrefs.BuildDirectory); } } private bool LocalIPsOnly { get { return false; } } // Privates private List<string> builds = new List<string>(); private float timeLastUpdatedBuilds = 0.0f; // Functions [MenuItem("HoloToolkit/Build Window", false, 0)] public static void OpenWindow() { BuildDeployWindow window = GetWindow<BuildDeployWindow>("Build Window") as BuildDeployWindow; if (window != null) { window.Show(); } } public static BuildDeployWindow GetBuildWindow() { return GetWindow<BuildDeployWindow>("Build Window") as BuildDeployWindow; } void OnEnable() { Setup(); } private void Setup() { this.titleContent = new GUIContent("Build Window"); this.minSize = new Vector2(600, 200); UpdateXdeStatus(); UpdateBuilds(); } private void UpdateXdeStatus() { XdeGuestLocator.FindGuestAddressAsync(); } private void OnGUI() { GUILayout.Space(GUISectionOffset); // Setup int buttonWidth_Quarter = Screen.width / 4; int buttonWidth_Half = Screen.width / 2; int buttonWidth_Full = Screen.width - 25; string appName = PlayerSettings.productName; // Build section GUILayout.BeginVertical(); GUILayout.Label("SLN"); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); // Build directory (and save setting, if it's changed) string curBuildDirectory = BuildDeployPrefs.BuildDirectory; string newBuildDirectory = EditorGUILayout.TextField(GUIHorizSpacer + "Build directory", curBuildDirectory); if (newBuildDirectory != curBuildDirectory) { BuildDeployPrefs.BuildDirectory = newBuildDirectory; curBuildDirectory = newBuildDirectory; } // Build SLN button using (new EditorGUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); GUI.enabled = ShouldOpenSLNBeEnabled; if (GUILayout.Button("Open SLN", GUILayout.Width(buttonWidth_Quarter))) { // Open SLN string slnFilename = Path.Combine(curBuildDirectory, PlayerSettings.productName + ".sln"); if (File.Exists(slnFilename)) { FileInfo slnFile = new FileInfo(slnFilename); System.Diagnostics.Process.Start(slnFile.FullName); } else if (EditorUtility.DisplayDialog("Solution Not Found", "We couldn't find the solution. Would you like to Build it?", "Yes, Build", "No")) { // Build SLN EditorApplication.delayCall += () => { BuildDeployTools.BuildSLN(curBuildDirectory); }; } } GUI.enabled = ShouldBuildSLNBeEnabled; if (GUILayout.Button("Build Visual Studio SLN", GUILayout.Width(buttonWidth_Half))) { // Build SLN EditorApplication.delayCall += () => { BuildDeployTools.BuildSLN(curBuildDirectory); }; } GUI.enabled = true; } // Build & Run button... using (new EditorGUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); GUI.enabled = ShouldBuildSLNBeEnabled; if (GUILayout.Button("Build SLN, Build APPX, then Install", GUILayout.Width(buttonWidth_Half))) { // Build SLN EditorApplication.delayCall += () => { BuildAndRun(appName); }; } GUI.enabled = true; } // Appx sub-section GUILayout.BeginVertical(); GUILayout.Label("APPX"); // MSBuild Ver (and save setting, if it's changed) string curMSBuildVer = BuildDeployPrefs.MsBuildVersion; string newMSBuildVer = EditorGUILayout.TextField(GUIHorizSpacer + "MSBuild Version", curMSBuildVer); if (newMSBuildVer != curMSBuildVer) { BuildDeployPrefs.MsBuildVersion = newMSBuildVer; curMSBuildVer = newMSBuildVer; } // Build config (and save setting, if it's changed) string curBuildConfig = BuildDeployPrefs.BuildConfig; string newBuildConfig = EditorGUILayout.TextField(GUIHorizSpacer + "Build Configuration", curBuildConfig); if (newBuildConfig != curBuildConfig) { BuildDeployPrefs.BuildConfig = newBuildConfig; curBuildConfig = newBuildConfig; } // Build APPX button using (new EditorGUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); float previousLabelWidth = EditorGUIUtility.labelWidth; // Force rebuild EditorGUIUtility.labelWidth = 50; bool curForceRebuildAppx = BuildDeployPrefs.ForceRebuild; bool newForceRebuildAppx = EditorGUILayout.Toggle("Rebuild", curForceRebuildAppx); if (newForceRebuildAppx != curForceRebuildAppx) { BuildDeployPrefs.ForceRebuild = newForceRebuildAppx; curForceRebuildAppx = newForceRebuildAppx; } // Increment version EditorGUIUtility.labelWidth = 110; bool curIncrementVersion = BuildDeployPrefs.IncrementBuildVersion; bool newIncrementVersion = EditorGUILayout.Toggle("Increment version", curIncrementVersion); if (newIncrementVersion != curIncrementVersion) { BuildDeployPrefs.IncrementBuildVersion = newIncrementVersion; curIncrementVersion = newIncrementVersion; } // Restore previous label width EditorGUIUtility.labelWidth = previousLabelWidth; // Build APPX GUI.enabled = ShouldBuildAppxBeEnabled; if (GUILayout.Button("Build APPX from SLN", GUILayout.Width(buttonWidth_Half))) { BuildDeployTools.BuildAppxFromSolution(appName, curMSBuildVer, curForceRebuildAppx, curBuildConfig, curBuildDirectory, curIncrementVersion); } GUI.enabled = true; } GUILayout.EndVertical(); GUILayout.EndVertical(); GUILayout.Space(GUISectionOffset); // Deploy section GUILayout.BeginVertical(); GUILayout.Label("Deploy"); // Target IPs (and save setting, if it's changed) string curTargetIps = BuildDeployPrefs.TargetIPs; if (!LocalIPsOnly) { string newTargetIPs = EditorGUILayout.TextField( new GUIContent(GUIHorizSpacer + "IP Address(es)", "IP(s) of target devices (e.g. 127.0.0.1;10.11.12.13)"), curTargetIps); if (newTargetIPs != curTargetIps) { BuildDeployPrefs.TargetIPs = newTargetIPs; curTargetIps = newTargetIPs; } } else { var locatorIsSearching = XdeGuestLocator.IsSearching; var locatorHasData = XdeGuestLocator.HasData; var xdeGuestIpAddress = XdeGuestLocator.GuestIpAddress; // Queue up a repaint if we're still busy, or we'll get stuck // in a disabled state. if (locatorIsSearching) { Repaint(); } var addressesToPresent = new List<string>(); addressesToPresent.Add("127.0.0.1"); if (!locatorIsSearching && locatorHasData) { addressesToPresent.Add(xdeGuestIpAddress.ToString()); } var previouslySavedAddress = addressesToPresent.IndexOf(curTargetIps); if (previouslySavedAddress == -1) { previouslySavedAddress = 0; } EditorGUILayout.BeginHorizontal(); if (locatorIsSearching && !locatorHasData) { GUI.enabled = false; } var selectedAddressIndex = EditorGUILayout.Popup(GUIHorizSpacer + "IP Address", previouslySavedAddress, addressesToPresent.ToArray()); if (GUILayout.Button(locatorIsSearching ? "Searching" : "Refresh", GUILayout.Width(buttonWidth_Quarter))) { UpdateXdeStatus(); } GUI.enabled = true; EditorGUILayout.EndHorizontal(); var selectedAddress = addressesToPresent[selectedAddressIndex]; if (curTargetIps != selectedAddress && !locatorIsSearching) { BuildDeployPrefs.TargetIPs = selectedAddress; } } // Username/Password (and save seeings, if changed) string curUsername = BuildDeployPrefs.DeviceUser; string newUsername = EditorGUILayout.TextField(GUIHorizSpacer + "Username", curUsername); string curPassword = BuildDeployPrefs.DevicePassword; string newPassword = EditorGUILayout.PasswordField(GUIHorizSpacer + "Password", curPassword); bool curFullReinstall = BuildDeployPrefs.FullReinstall; bool newFullReinstall = EditorGUILayout.Toggle( new GUIContent(GUIHorizSpacer + "Uninstall first", "Uninstall application before installing"), curFullReinstall); if ((newUsername != curUsername) || (newPassword != curPassword) || (newFullReinstall != curFullReinstall)) { BuildDeployPrefs.DeviceUser = newUsername; BuildDeployPrefs.DevicePassword = newPassword; BuildDeployPrefs.FullReinstall = newFullReinstall; curUsername = newUsername; curPassword = newPassword; curFullReinstall = newFullReinstall; } // Build list (with install buttons) if (this.builds.Count == 0) { GUILayout.Label(GUIHorizSpacer + "*** No builds found in build directory", EditorStyles.boldLabel); } else { foreach (var fullBuildLocation in this.builds) { int lastBackslashIndex = fullBuildLocation.LastIndexOf("\\"); var directoryDate = Directory.GetLastWriteTime(fullBuildLocation).ToString("yyyy/MM/dd HH:mm:ss"); string packageName = fullBuildLocation.Substring(lastBackslashIndex + 1); EditorGUILayout.BeginHorizontal(); GUILayout.Space(GUISectionOffset + 15); if (GUILayout.Button("Install", GUILayout.Width(120.0f))) { string thisBuildLocation = fullBuildLocation; string[] IPlist = ParseIPList(curTargetIps); EditorApplication.delayCall += () => { InstallAppOnDevicesList(thisBuildLocation, curFullReinstall, IPlist); }; } GUILayout.Space(5); GUILayout.Label(packageName + " (" + directoryDate + ")"); EditorGUILayout.EndHorizontal(); } EditorGUILayout.Separator(); } GUILayout.EndVertical(); GUILayout.Space(GUISectionOffset); // Utilities section GUILayout.BeginVertical(); GUILayout.Label("Utilities"); // Open web portal using (new EditorGUILayout.HorizontalScope()) { GUI.enabled = ShouldWebPortalBeEnabled; GUILayout.FlexibleSpace(); if (GUILayout.Button("Open Device Portal", GUILayout.Width(buttonWidth_Full))) { OpenWebPortalForIPs(curTargetIps); } GUI.enabled = true; } // Launch app.. using (new EditorGUILayout.HorizontalScope()) { GUI.enabled = ShouldLaunchAppBeEnabled; GUILayout.FlexibleSpace(); if (GUILayout.Button("Launch Application", GUILayout.Width(buttonWidth_Full))) { // If already running, kill it (button is a toggle) if (IsAppRunning_FirstIPCheck(appName, curTargetIps)) { KillAppOnIPs(curTargetIps); } else { LaunchAppOnIPs(curTargetIps); } } GUI.enabled = true; } // Log file using (new EditorGUILayout.HorizontalScope()) { GUI.enabled = ShouldLogViewBeEnabled; GUILayout.FlexibleSpace(); if (GUILayout.Button("View Log File", GUILayout.Width(buttonWidth_Full))) { OpenLogFileForIPs(curTargetIps); } GUI.enabled = true; } // Uninstall... using (new EditorGUILayout.HorizontalScope()) { GUI.enabled = ShouldLogViewBeEnabled; GUILayout.FlexibleSpace(); if (GUILayout.Button("Uninstall Application", GUILayout.Width(buttonWidth_Full))) { string[] IPlist = ParseIPList(curTargetIps); EditorApplication.delayCall += () => { UninstallAppOnDevicesList(IPlist); }; } GUI.enabled = true; } GUILayout.EndVertical(); } public void Install() { string fullBuildLocation = CalcMostRecentBuild(); string[] IPlist = ParseIPList(BuildDeployPrefs.TargetIPs); InstallAppOnDevicesList(fullBuildLocation, BuildDeployPrefs.FullReinstall, IPlist); } public void BuildAndRun(string appName) { // First build SLN if (!BuildDeployTools.BuildSLN(BuildDeployPrefs.BuildDirectory, false)) { return; } // Next, APPX if (!BuildDeployTools.BuildAppxFromSolution( appName, BuildDeployPrefs.MsBuildVersion, BuildDeployPrefs.ForceRebuild, BuildDeployPrefs.BuildConfig, BuildDeployPrefs.BuildDirectory, BuildDeployPrefs.IncrementBuildVersion)) { return; } // Next, Install string fullBuildLocation = CalcMostRecentBuild(); string[] IPlist = ParseIPList(BuildDeployPrefs.TargetIPs); InstallAppOnDevicesList(fullBuildLocation, BuildDeployPrefs.FullReinstall, IPlist); } private string CalcMostRecentBuild() { UpdateBuilds(); DateTime mostRecent = DateTime.MinValue; string mostRecentBuild = ""; foreach (var fullBuildLocation in this.builds) { DateTime directoryDate = Directory.GetLastWriteTime(fullBuildLocation); if (directoryDate > mostRecent) { mostRecentBuild = fullBuildLocation; mostRecent = directoryDate; } } return mostRecentBuild; } private string CalcPackageFamilyName() { // Find the manifest string[] manifests = Directory.GetFiles(BuildDeployPrefs.AbsoluteBuildDirectory, "Package.appxmanifest", SearchOption.AllDirectories); if (manifests.Length == 0) { Debug.LogError("Unable to find manifest file for build (in path - " + BuildDeployPrefs.AbsoluteBuildDirectory + ")"); return ""; } string manifest = manifests[0]; // Parse it using (XmlTextReader reader = new XmlTextReader(manifest)) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Name.Equals("identity", StringComparison.OrdinalIgnoreCase)) { while (reader.MoveToNextAttribute()) { if (reader.Name.Equals("name", StringComparison.OrdinalIgnoreCase)) { return reader.Value; } } } break; } } } Debug.LogError("Unable to find PackageFamilyName in manifest file (" + manifest + ")"); return ""; } private void InstallAppOnDevicesList(string buildPath, bool uninstallBeforeInstall, string[] targetList) { string packageFamilyName = CalcPackageFamilyName(); if (string.IsNullOrEmpty(packageFamilyName)) { return; } for (int i = 0; i < targetList.Length; i++) { try { bool completedUninstall = false; string IP = FinalizeIP(targetList[i]); if (BuildDeployPrefs.FullReinstall && BuildDeployPortal.IsAppInstalled(packageFamilyName, new BuildDeployPortal.ConnectInfo(IP, BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword))) { EditorUtility.DisplayProgressBar("Installing on devices", "Uninstall (" + IP + ")", (float)i / (float)targetList.Length); if (!UninstallApp(packageFamilyName, IP)) { Debug.LogError("Uninstall failed - skipping install (" + IP + ")"); continue; } completedUninstall = true; } EditorUtility.DisplayProgressBar("Installing on devices", "Install (" + IP + ")", (float)(i + (completedUninstall ? 0.5f : 0.0f)) / (float)targetList.Length); InstallApp(buildPath, packageFamilyName, IP); } catch (Exception ex) { Debug.LogError(ex.ToString()); } } EditorUtility.ClearProgressBar(); } private bool InstallApp(string buildPath, string appName, string targetDevice) { // Get the appx path FileInfo[] files = (new DirectoryInfo(buildPath)).GetFiles("*.appx"); files = (files.Length == 0) ? (new DirectoryInfo(buildPath)).GetFiles("*.appxbundle") : files; if (files.Length == 0) { Debug.LogError("No APPX found in folder build folder (" + buildPath + ")"); return false; } // Connection info var connectInfo = new BuildDeployPortal.ConnectInfo(targetDevice, BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword); // Kick off the install Debug.Log("Installing build on: " + targetDevice); return BuildDeployPortal.InstallApp(files[0].FullName, connectInfo); } private void UninstallAppOnDevicesList(string[] targetList) { string packageFamilyName = CalcPackageFamilyName(); if (string.IsNullOrEmpty(packageFamilyName)) { return; } try { for (int i = 0; i < targetList.Length; i++) { string IP = FinalizeIP(targetList[i]); EditorUtility.DisplayProgressBar("Uninstalling application", "Uninstall (" + IP + ")", (float)i / (float)targetList.Length); UninstallApp(packageFamilyName, IP); } } catch (Exception ex) { Debug.LogError(ex.ToString()); } EditorUtility.ClearProgressBar(); } private bool UninstallApp(string packageFamilyName, string targetDevice) { // Connection info var connectInfo = new BuildDeployPortal.ConnectInfo(targetDevice, BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword); // Kick off the install Debug.Log("Uninstall build: " + targetDevice); return BuildDeployPortal.UninstallApp(packageFamilyName, connectInfo); } private void UpdateBuilds() { this.builds.Clear(); try { List<string> appPackageDirectories = new List<string>(); string[] buildList = Directory.GetDirectories(BuildDeployPrefs.AbsoluteBuildDirectory); foreach (string appBuild in buildList) { string appPackageDirectory = appBuild + @"\AppPackages"; if (Directory.Exists(appPackageDirectory)) { appPackageDirectories.AddRange(Directory.GetDirectories(appPackageDirectory)); } } IEnumerable<string> selectedDirectories = from string directory in appPackageDirectories orderby Directory.GetLastWriteTime(directory) descending select Path.GetFullPath(directory); this.builds.AddRange(selectedDirectories); } catch (DirectoryNotFoundException) { } timeLastUpdatedBuilds = Time.realtimeSinceStartup; } void Update() { if ((Time.realtimeSinceStartup - timeLastUpdatedBuilds) > UpdateBuildsPeriod) { UpdateBuilds(); } } public static string[] ParseIPList(string IPs) { string[] IPlist = { }; if (IPs == null || IPs == "") return IPlist; string[] separators = { ";", " ", "," }; IPlist = IPs.Split(separators, System.StringSplitOptions.RemoveEmptyEntries); return IPlist; } static string FinalizeIP(string ip) { // If it's local, add the port if (ip == "127.0.0.1") { ip += ":10080"; } return ip; } public static void OpenWebPortalForIPs(string IPs) { string[] ipList = ParseIPList(IPs); for (int i = 0; i < ipList.Length; i++) { string url = string.Format("http://{0}", FinalizeIP(ipList[i])); // Run the process System.Diagnostics.Process.Start(url); } } bool IsAppRunning_FirstIPCheck(string appName, string targetIPs) { // Just pick the first one and use it... string[] IPlist = ParseIPList(targetIPs); if (IPlist.Length > 0) { string targetIP = FinalizeIP(IPlist[0]); return BuildDeployPortal.IsAppRunning( appName, new BuildDeployPortal.ConnectInfo(targetIP, BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword)); } return false; } public void LaunchAppOnIPs(string targetIPs) { string packageFamilyName = CalcPackageFamilyName(); if (string.IsNullOrEmpty(packageFamilyName)) { return; } string[] IPlist = ParseIPList(targetIPs); for (int i = 0; i < IPlist.Length; i++) { string targetIP = FinalizeIP(IPlist[i]); Debug.Log("Launch app on: " + targetIP); BuildDeployPortal.LaunchApp( packageFamilyName, new BuildDeployPortal.ConnectInfo(targetIP, BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword)); } } public void KillAppOnIPs(string targetIPs) { string packageFamilyName = CalcPackageFamilyName(); if (string.IsNullOrEmpty(packageFamilyName)) { return; } string[] IPlist = ParseIPList(targetIPs); for (int i = 0; i < IPlist.Length; i++) { string targetIP = FinalizeIP(IPlist[i]); Debug.Log("Kill app on: " + targetIP); BuildDeployPortal.KillApp( packageFamilyName, new BuildDeployPortal.ConnectInfo(targetIP, BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword)); } } public void OpenLogFileForIPs(string IPs) { string packageFamilyName = CalcPackageFamilyName(); if (string.IsNullOrEmpty(packageFamilyName)) { return; } string[] ipList = ParseIPList(IPs); for (int i = 0; i < ipList.Length; i++) { // Use the Device Portal REST API BuildDeployPortal.DeviceLogFile_View( packageFamilyName, new BuildDeployPortal.ConnectInfo(FinalizeIP(ipList[i]), BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword)); } } } }
using System; using Csla; using Csla.Data; using DalEf; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; using BusinessObjects.CoreBusinessClasses; using System.Collections.Generic; namespace BusinessObjects.Projects { [Serializable] public partial class cProjects_Project_TeamMemebers: CoreBusinessChildClass<cProjects_Project_TeamMemebers> { public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty); #if !SILVERLIGHT [System.ComponentModel.DataObjectField(true, true)] #endif public System.Int32 Id { get { return GetProperty(IdProperty); } internal set { SetProperty(IdProperty, value); } } private static readonly PropertyInfo< System.Int32 > projects_ProjectIdProperty = RegisterProperty<System.Int32>(p => p.Projects_ProjectId, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 Projects_ProjectId { get { return GetProperty(projects_ProjectIdProperty); } set { SetProperty(projects_ProjectIdProperty, value); } } private static readonly PropertyInfo<System.Int32> mDSubjects_SubjectIdProperty = RegisterProperty<System.Int32>(p => p.MDSubjects_SubjectId, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 MDSubjects_SubjectId { get { return GetProperty(mDSubjects_SubjectIdProperty); } set { SetProperty(mDSubjects_SubjectIdProperty, value); } } private static readonly PropertyInfo< System.Int32? > mDEntities_ServiceIdProperty = RegisterProperty<System.Int32?>(p => p.MDEntities_ServiceId, string.Empty,(System.Int32?)null); public System.Int32? MDEntities_ServiceId { get { return GetProperty(mDEntities_ServiceIdProperty); } set { SetProperty(mDEntities_ServiceIdProperty, value); } } private static readonly PropertyInfo< System.Decimal? > contractorRebillRatePerHourProperty = RegisterProperty<System.Decimal?>(p => p.ContractorRebillRatePerHour, string.Empty, (System.Decimal?)null); public System.Decimal? ContractorRebillRatePerHour { get { return GetProperty(contractorRebillRatePerHourProperty); } set { SetProperty(contractorRebillRatePerHourProperty, value); } } private static readonly PropertyInfo< System.Decimal? > contractoRebillFlatAmountProperty = RegisterProperty<System.Decimal?>(p => p.ContractoRebillFlatAmount, string.Empty, (System.Decimal?)null); public System.Decimal? ContractoRebillFlatAmount { get { return GetProperty(contractoRebillFlatAmountProperty); } set { SetProperty(contractoRebillFlatAmountProperty, value); } } /// <summary> /// Used for optimistic concurrency. /// </summary> [NotUndoable] internal System.Byte[] LastChanged = new System.Byte[8]; internal static cProjects_Project_TeamMemebers NewProjects_Project_TeamMemebers() { return DataPortal.CreateChild<cProjects_Project_TeamMemebers>(); } public static cProjects_Project_TeamMemebers GetcProjects_Project_TeamMemebers(Projects_Project_TeamMemebersCol data) { return DataPortal.FetchChild<cProjects_Project_TeamMemebers>(data); } #region Data Access [RunLocal] protected override void Child_Create() { BusinessRules.CheckRules(); } private void Child_Fetch(Projects_Project_TeamMemebersCol data) { LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<int>(projects_ProjectIdProperty, data.Projects_ProjectId); LoadProperty<int>(mDSubjects_SubjectIdProperty, data.MDSubjects_SubjectId); LoadProperty<int?>(mDEntities_ServiceIdProperty, data.MDEntities_ServiceId); LoadProperty<decimal?>(contractorRebillRatePerHourProperty, data.ContractorRebillRatePerHour); LoadProperty<decimal?>(contractoRebillFlatAmountProperty, data.ContractoRebillFlatAmount); LastChanged = data.LastChanged; BusinessRules.CheckRules(); } private void Child_Insert(Projects_Project parent) { using (var ctx = ObjectContextManager<ProjectsEntities>.GetManager("ProjectsEntities")) { var data = new Projects_Project_TeamMemebersCol(); data.Projects_Project = parent; data.Projects_ProjectId = ReadProperty<int>(projects_ProjectIdProperty); data.MDSubjects_SubjectId = ReadProperty<int>(mDSubjects_SubjectIdProperty); data.MDEntities_ServiceId = ReadProperty<int?>(mDEntities_ServiceIdProperty); data.ContractorRebillRatePerHour = ReadProperty<decimal?>(contractorRebillRatePerHourProperty); data.ContractoRebillFlatAmount = ReadProperty<decimal?>(contractoRebillFlatAmountProperty); ctx.ObjectContext.AddToProjects_Project_TeamMemebersCol(data); data.PropertyChanged += (o, e) => { if (e.PropertyName == "Id") { LoadProperty<int>(IdProperty, data.Id); LoadProperty<int>(projects_ProjectIdProperty, data.Projects_ProjectId); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LastChanged = data.LastChanged; } }; } } private void Child_Update() { using (var ctx = ObjectContextManager<ProjectsEntities>.GetManager("ProjectsEntities")) { var data = new Projects_Project_TeamMemebersCol(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; //data.SubjectId = parent.Id; ctx.ObjectContext.Attach(data); data.Projects_ProjectId = ReadProperty<int>(projects_ProjectIdProperty); data.MDSubjects_SubjectId = ReadProperty<int>(mDSubjects_SubjectIdProperty); data.MDEntities_ServiceId = ReadProperty<int?>(mDEntities_ServiceIdProperty); data.ContractorRebillRatePerHour = ReadProperty<decimal?>(contractorRebillRatePerHourProperty); data.ContractoRebillFlatAmount = ReadProperty<decimal?>(contractoRebillFlatAmountProperty); data.PropertyChanged += (o, e) => { if (e.PropertyName == "LastChanged") LastChanged = data.LastChanged; }; } } private void Child_DeleteSelf() { using (var ctx = ObjectContextManager<ProjectsEntities>.GetManager("ProjectsEntities")) { var data = new Projects_Project_TeamMemebersCol(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; //data.SubjectId = parent.Id; ctx.ObjectContext.Attach(data); ctx.ObjectContext.DeleteObject(data); } } #endregion public void MarkChild() { this.MarkAsChild(); } } [Serializable] public partial class cProjects_Project_TeamMemebersCol : BusinessListBase<cProjects_Project_TeamMemebersCol,cProjects_Project_TeamMemebers> { internal static cProjects_Project_TeamMemebersCol NewProjects_Project_TeamMemebersCol() { return DataPortal.CreateChild<cProjects_Project_TeamMemebersCol>(); } public static cProjects_Project_TeamMemebersCol GetcProjects_Project_TeamMemebersCol(IEnumerable<Projects_Project_TeamMemebersCol> dataSet) { var childList = new cProjects_Project_TeamMemebersCol(); childList.Fetch(dataSet); return childList; } #region Data Access private void Fetch(IEnumerable<Projects_Project_TeamMemebersCol> dataSet) { RaiseListChangedEvents = false; foreach (var data in dataSet) this.Add(cProjects_Project_TeamMemebers.GetcProjects_Project_TeamMemebers(data)); RaiseListChangedEvents = true; } #endregion //Data Access } }
// 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.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal partial class AttributeNamedParameterCompletionProvider : AbstractCompletionProvider { private const string EqualsString = "="; private const string SpaceEqualsString = " ="; private const string ColonString = ":"; public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options) { return CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); } protected override async Task<bool> IsExclusiveAsync(Document document, int caretPosition, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken) { var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = syntaxTree.FindTokenOnLeftOfPosition(caretPosition, cancellationToken) .GetPreviousTokenIfTouchingWord(caretPosition); return IsAfterNameColonArgument(token) || IsAfterNameEqualsArgument(token); } private bool IsAfterNameColonArgument(SyntaxToken token) { var argumentList = token.Parent as AttributeArgumentListSyntax; if (token.Kind() == SyntaxKind.CommaToken && argumentList != null) { foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { var node = item.AsNode() as AttributeArgumentSyntax; if (node.NameColon != null) { return true; } } } } return false; } private bool IsAfterNameEqualsArgument(SyntaxToken token) { var argumentList = token.Parent as AttributeArgumentListSyntax; if (token.Kind() == SyntaxKind.CommaToken && argumentList != null) { foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { var node = item.AsNode() as AttributeArgumentSyntax; if (node.NameEquals != null) { return true; } } } } return false; } protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync( Document document, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken) { var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.IsInNonUserCode(position, cancellationToken)) { return null; } var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.Kind() != SyntaxKind.OpenParenToken && token.Kind() != SyntaxKind.CommaToken) { return null; } var attributeArgumentList = token.Parent as AttributeArgumentListSyntax; var attributeSyntax = token.Parent.Parent as AttributeSyntax; if (attributeSyntax == null || attributeArgumentList == null) { return null; } // We actually want to collect two sets of named parameters to present the user. The // normal named parameters that come from the attribute constructors. These will be // presented like "foo:". And also the named parameters that come from the writable // fields/properties in the attribute. These will be presented like "bar =". var existingNamedParameters = GetExistingNamedParameters(attributeArgumentList, position); var workspace = document.Project.Solution.Workspace; var semanticModel = await document.GetSemanticModelForNodeAsync(attributeSyntax, cancellationToken).ConfigureAwait(false); var nameColonItems = await GetNameColonItemsAsync(workspace, semanticModel, position, token, attributeSyntax, existingNamedParameters, cancellationToken).ConfigureAwait(false); var nameEqualsItems = await GetNameEqualsItemsAsync(workspace, semanticModel, position, token, attributeSyntax, existingNamedParameters, cancellationToken).ConfigureAwait(false); // If we're after a name= parameter, then we only want to show name= parameters. if (IsAfterNameEqualsArgument(token)) { return nameEqualsItems; } return nameColonItems.Concat(nameEqualsItems); } private async Task<IEnumerable<CompletionItem>> GetNameEqualsItemsAsync(Workspace workspace, SemanticModel semanticModel, int position, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters, CancellationToken cancellationToken) { var attributeNamedParameters = GetAttributeNamedParameters(semanticModel, position, attributeSyntax, cancellationToken); var unspecifiedNamedParameters = attributeNamedParameters.Where(p => !existingNamedParameters.Contains(p.Name)); var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); return from p in attributeNamedParameters where !existingNamedParameters.Contains(p.Name) select new CompletionItem( this, p.Name.ToIdentifierToken().ToString() + SpaceEqualsString, CompletionUtilities.GetTextChangeSpan(text, position), CommonCompletionUtilities.CreateDescriptionFactory(workspace, semanticModel, token.SpanStart, p), p.GetGlyph(), sortText: p.Name, rules: ItemRules.Instance); } private async Task<IEnumerable<CompletionItem>> GetNameColonItemsAsync( Workspace workspace, SemanticModel semanticModel, int position, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters, CancellationToken cancellationToken) { var parameterLists = GetParameterLists(semanticModel, position, attributeSyntax, cancellationToken); parameterLists = parameterLists.Where(pl => IsValid(pl, existingNamedParameters)); var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); return from pl in parameterLists from p in pl where !existingNamedParameters.Contains(p.Name) select new CompletionItem( this, p.Name.ToIdentifierToken().ToString() + ColonString, CompletionUtilities.GetTextChangeSpan(text, position), CommonCompletionUtilities.CreateDescriptionFactory(workspace, semanticModel, token.SpanStart, p), p.GetGlyph(), sortText: p.Name, rules: ItemRules.Instance); } private bool IsValid(ImmutableArray<IParameterSymbol> parameterList, ISet<string> existingNamedParameters) { return existingNamedParameters.Except(parameterList.Select(p => p.Name)).IsEmpty(); } private ISet<string> GetExistingNamedParameters(AttributeArgumentListSyntax argumentList, int position) { var existingArguments1 = argumentList.Arguments.Where(a => a.Span.End <= position) .Where(a => a.NameColon != null) .Select(a => a.NameColon.Name.Identifier.ValueText); var existingArguments2 = argumentList.Arguments.Where(a => a.Span.End <= position) .Where(a => a.NameEquals != null) .Select(a => a.NameEquals.Name.Identifier.ValueText); return existingArguments1.Concat(existingArguments2).ToSet(); } private IEnumerable<ImmutableArray<IParameterSymbol>> GetParameterLists( SemanticModel semanticModel, int position, AttributeSyntax attribute, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol; if (within != null && attributeType != null) { return attributeType.InstanceConstructors.Where(c => c.IsAccessibleWithin(within)) .Select(c => c.Parameters); } return SpecializedCollections.EmptyEnumerable<ImmutableArray<IParameterSymbol>>(); } private IEnumerable<ISymbol> GetAttributeNamedParameters( SemanticModel semanticModel, int position, AttributeSyntax attribute, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol; return attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Reflection; using System.Collections.Generic; namespace System.Reflection.Tests { public class MethodInfoCreateDelegateTests { //Create Open Instance delegate to a public method [Fact] public void TestCreateDelegate1() { Type typeTestClass = typeof(ClassA); RunBasicTestsHelper(typeTestClass); } //Inheritance Tests [Fact] public void TestCreateDelegate2() { Type typeTestClass = typeof(ClassA); Type TestSubClassType = typeof(SubClassA); RunInheritanceTestsHelper(typeTestClass, TestSubClassType); } //Generic Tests [Fact] public void TestCreateDelegate3() { Type typeGenericClassString = typeof(GenericClass<String>); RunGenericTestsHelper(typeGenericClassString); } //create open instance delegate with incorrect delegate type [Fact] public void TestCreateDelegate4() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicInstanceMethod = GetMethod(typeof(ClassA), "PublicInstanceMethod"); ClassA classAObj = new ClassA(); Assert.Throws<ArgumentException>(() => { miPublicInstanceMethod.CreateDelegate(typeof(Delegate_Void_Int)); }); } //Verify ArgumentNullExcpeption when type is null [Fact] public void TestCreateDelegate5() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicInstanceMethod = GetMethod(typeof(ClassA), "PublicInstanceMethod"); ClassA classAObj = new ClassA(); Assert.Throws<ArgumentNullException>(() => { miPublicInstanceMethod.CreateDelegate(null); }); } //create closed instance delegate with incorrect delegate type [Fact] public void TestCreateDelegate6() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicInstanceMethod = GetMethod(typeof(ClassA), "PublicInstanceMethod"); ClassA classAObj = new ClassA(); Assert.Throws<ArgumentException>(() => { miPublicInstanceMethod.CreateDelegate(typeof(Delegate_TC_Int), TestClass); }); } //Verify ArgumentNullExcpeption when type is null [Fact] public void TestCreateDelegate7() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicInstanceMethod = GetMethod(typeof(ClassA), "PublicInstanceMethod"); ClassA classAObj = new ClassA(); Assert.Throws<ArgumentNullException>(() => { miPublicInstanceMethod.CreateDelegate(null, TestClass); }); } //closed instance delegate with incorrect object type [Fact] public void TestCreateDelegate8() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicInstanceMethod = GetMethod(typeof(ClassA), "PublicInstanceMethod"); ClassA classAObj = new ClassA(); Assert.Throws<ArgumentException>(() => { miPublicInstanceMethod.CreateDelegate(typeof(Delegate_Void_Int), new DummyClass()); }); } //create closed static method with inccorect argument [Fact] public void TestCreateDelegate9() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicInstanceMethod = GetMethod(typeof(ClassA), "PublicInstanceMethod"); ClassA classAObj = new ClassA(); Assert.Throws<ArgumentException>(() => { miPublicInstanceMethod.CreateDelegate(typeof(Delegate_Void_Str), new DummyClass()); }); } [Fact] public void TestCreateDelegate10() { ClassA TestClass = (ClassA)Activator.CreateInstance(typeof(ClassA)); MethodInfo miPublicStructMethod = GetMethod(typeof(ClassA), "PublicStructMethod"); ClassA classAObj = new ClassA(); Delegate dlgt = miPublicStructMethod.CreateDelegate(typeof(Delegate_DateTime_Str)); Object retValue = ((Delegate_DateTime_Str)dlgt).DynamicInvoke(new Object[] { classAObj, null }); Object actualReturnValue = classAObj.PublicStructMethod(new DateTime()); Assert.True(retValue.Equals(actualReturnValue)); } public void RunBasicTestsHelper(Type typeTestClass) { ClassA TestClass = (ClassA)Activator.CreateInstance(typeTestClass); MethodInfo miPublicInstanceMethod = GetMethod(typeTestClass, "PublicInstanceMethod"); MethodInfo miPrivateInstanceMethod = GetMethod(typeTestClass, "PrivateInstanceMethod"); MethodInfo miPublicStaticMethod = GetMethod(typeTestClass, "PublicStaticMethod"); Delegate dlgt = miPublicInstanceMethod.CreateDelegate(typeof(Delegate_TC_Int)); Object retValue = ((Delegate_TC_Int)dlgt).DynamicInvoke(new Object[] { TestClass }); Assert.True(retValue.Equals(TestClass.PublicInstanceMethod())); Assert.NotNull(miPrivateInstanceMethod); dlgt = miPrivateInstanceMethod.CreateDelegate(typeof(Delegate_TC_Int)); retValue = ((Delegate_TC_Int)dlgt).DynamicInvoke(new Object[] { TestClass }); Assert.True(retValue.Equals(21)); dlgt = miPublicInstanceMethod.CreateDelegate(typeof(Delegate_Void_Int), TestClass); retValue = ((Delegate_Void_Int)dlgt).DynamicInvoke(null); Assert.True(retValue.Equals(TestClass.PublicInstanceMethod())); dlgt = miPublicStaticMethod.CreateDelegate(typeof(Delegate_Str_Str)); retValue = ((Delegate_Str_Str)dlgt).DynamicInvoke(new Object[] { "85" }); Assert.True(retValue.Equals("85")); dlgt = miPublicStaticMethod.CreateDelegate(typeof(Delegate_Void_Str), "93"); retValue = ((Delegate_Void_Str)dlgt).DynamicInvoke(null); Assert.True(retValue.Equals("93")); } public void RunInheritanceTestsHelper(Type typeTestClass, Type TestSubClassType) { SubClassA TestSubClass = (SubClassA)Activator.CreateInstance(TestSubClassType); ClassA TestClass = (ClassA)Activator.CreateInstance(typeTestClass); MethodInfo miPublicInstanceMethod = GetMethod(typeTestClass, "PublicInstanceMethod"); Delegate dlgt = miPublicInstanceMethod.CreateDelegate(typeof(Delegate_TC_Int)); object retValue = ((Delegate_TC_Int)dlgt).DynamicInvoke(new Object[] { TestSubClass }); Assert.True(retValue.Equals(TestSubClass.PublicInstanceMethod())); dlgt = miPublicInstanceMethod.CreateDelegate(typeof(Delegate_Void_Int), TestSubClass); retValue = ((Delegate_Void_Int)dlgt).DynamicInvoke(); Assert.True(retValue.Equals(TestSubClass.PublicInstanceMethod())); } public void RunGenericTestsHelper(Type typeGenericClassString) { GenericClass<String> genericClass = (GenericClass<String>)Activator.CreateInstance(typeGenericClassString); MethodInfo miMethod1String = GetMethod(typeGenericClassString, "Method1"); MethodInfo miMethod2String = GetMethod(typeGenericClassString, "Method2"); MethodInfo miMethod2IntGeneric = miMethod2String.MakeGenericMethod(new Type[] { typeof(int) }); MethodInfo miMethod2StringGeneric = miMethod2String.MakeGenericMethod(new Type[] { typeof(String) }); Delegate dlgt = miMethod1String.CreateDelegate(typeof(Delegate_GC_T_T<String>)); object retValue = ((Delegate_GC_T_T<String>)dlgt).DynamicInvoke(new Object[] { genericClass, "TestGeneric" }); Assert.True(retValue.Equals(genericClass.Method1("TestGeneric"))); dlgt = miMethod1String.CreateDelegate(typeof(Delegate_T_T<String>), genericClass); retValue = ((Delegate_T_T<String>)dlgt).DynamicInvoke(new Object[] { "TestGeneric" }); Assert.True(retValue.Equals(genericClass.Method1("TestGeneric"))); dlgt = miMethod2IntGeneric.CreateDelegate(typeof(Delegate_T_T<int>)); retValue = ((Delegate_T_T<int>)dlgt).DynamicInvoke(new Object[] { 58 }); Assert.True(retValue.Equals(58)); dlgt = miMethod2StringGeneric.CreateDelegate(typeof(Delegate_Void_T<String>), "firstArg"); retValue = ((Delegate_Void_T<String>)dlgt).DynamicInvoke(); Assert.True(retValue.Equals("firstArg")); } // Gets MethodInfo object from current class public static MethodInfo GetMethod(string method) { return GetMethod(typeof(MethodInfoCreateDelegateTests), method); } //Gets MethodInfo object from a Type public static MethodInfo GetMethod(Type t, string method) { TypeInfo ti = t.GetTypeInfo(); IEnumerator<MethodInfo> alldefinedMethods = ti.DeclaredMethods.GetEnumerator(); MethodInfo mi = null; while (alldefinedMethods.MoveNext()) { if (alldefinedMethods.Current.Name.Equals(method)) { //found method mi = alldefinedMethods.Current; break; } } return mi; } } public delegate int Delegate_TC_Int(ClassA tc); public delegate int Delegate_Void_Int(); public delegate String Delegate_Str_Str(String x); public delegate String Delegate_Void_Str(); public delegate String Delegate_DateTime_Str(ClassA tc, DateTime dt); public delegate T Delegate_GC_T_T<T>(GenericClass<T> gc, T x); public delegate T Delegate_T_T<T>(T x); public delegate T Delegate_Void_T<T>(); public class ClassA { public virtual int PublicInstanceMethod() { return 17; } private int PrivateInstanceMethod() { return 21; } public static String PublicStaticMethod(String x) { return x; } public string PublicStructMethod(DateTime dt) { return dt.ToString(); } } public class SubClassA : ClassA { public override int PublicInstanceMethod() { return 79; } } public class DummyClass { public int DummyMethod() { return -1; } public override String ToString() { return "DummyClass"; } } public class GenericClass<T> { public T Method1(T t) { return t; } public static S Method2<S>(S s) { return s; } } }
// // Copyright (c) 2008-2019 the Urho3D project. // Copyright (c) 2017-2020 the rbfx project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Urho3DNet { /// 2x2 matrix for rotation and scaling. [StructLayout(LayoutKind.Sequential)] public struct Matrix2 : IEquatable<Matrix2> { /// Construct from values. public Matrix2(float v00 = 1, float v01 = 0, float v10 = 0, float v11 = 1) { M00 = v00; M01 = v01; M10 = v10; M11 = v11; } /// Construct from a float array. public Matrix2(IReadOnlyList<float> data) { M00 = data[0]; M01 = data[1]; M10 = data[2]; M11 = data[3]; } /// Test for equality with another matrix without epsilon. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(in Matrix2 lhs, in Matrix2 rhs) { return !(lhs != rhs); } /// Test for inequality with another matrix without epsilon. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(in Matrix2 lhs, in Matrix2 rhs) { return lhs.M00 != rhs.M00 || lhs.M01 != rhs.M01 || lhs.M10 != rhs.M10 || lhs.M11 != rhs.M11; } /// Multiply a Vector2. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator *(in Matrix2 lhs, in Vector2 rhs) { return new Vector2( lhs.M00 * rhs.X + lhs.M01 * rhs.Y, lhs.M10 * rhs.X + lhs.M11 * rhs.Y ); } /// Add a matrix. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix2 operator +(in Matrix2 lhs, in Matrix2 rhs) { return new Matrix2( lhs.M00 + rhs.M00, lhs.M01 + rhs.M01, lhs.M10 + rhs.M10, lhs.M11 + rhs.M11 ); } /// Subtract a matrix. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix2 operator -(in Matrix2 lhs, in Matrix2 rhs) { return new Matrix2( lhs.M00 - rhs.M00, lhs.M01 - rhs.M01, lhs.M10 - rhs.M10, lhs.M11 - rhs.M11 ); } /// Multiply with a scalar. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix2 operator *(in Matrix2 lhs, float rhs) { return new Matrix2( lhs.M00 * rhs, lhs.M01 * rhs, lhs.M10 * rhs, lhs.M11 * rhs ); } /// Multiply a matrix. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix2 operator *(in Matrix2 lhs, in Matrix2 rhs) { return new Matrix2( lhs.M00 * rhs.M00 + lhs.M01 * rhs.M10, lhs.M00 * rhs.M01 + lhs.M01 * rhs.M11, lhs.M10 * rhs.M00 + lhs.M11 * rhs.M10, lhs.M10 * rhs.M01 + lhs.M11 * rhs.M11 ); } /// Multiply a 2x2 matrix with a scalar. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix2 operator *(float lhs, in Matrix2 rhs) { return rhs * lhs; } /// Set scaling elements. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetScale(in Vector2 scale) { M00 = scale.X; M11 = scale.Y; } /// Set uniform scaling elements. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetScale(float scale) { M00 = scale; M11 = scale; } /// Return the scaling part. public Vector2 Scale => new Vector2( (float) Math.Sqrt(M00 * M00 + M10 * M10), (float) Math.Sqrt(M01 * M01 + M11 * M11) ); /// Return transpose. public Matrix2 Transposed => new Matrix2(M00, M10, M01, M11); /// Return scaled by a vector. [MethodImpl(MethodImplOptions.AggressiveInlining)] public Matrix2 Scaled(in Vector2 scale) { return new Matrix2( M00 * scale.X, M01 * scale.Y, M10 * scale.X, M11 * scale.Y ); } /// Test for equality with another matrix with epsilon. public bool Equals(Matrix2 rhs) { return MathDefs.Equals(M00, rhs.M00) && MathDefs.Equals(M01, rhs.M01) && MathDefs.Equals(M10, rhs.M10) && MathDefs.Equals(M11, rhs.M11); } /// Return inverse. public Matrix2 Inverse { get { float det = M00 * M11 - M01 * M10; float invDet = 1.0f / det; return new Matrix2(M11, -M01, -M10, M00) * invDet; } } /// Return float data. public float[] Data => new[] {M00, M01, M10, M11}; /// Return as string. public override string ToString() { return $"{M00} {M01} {M10} {M11}"; } public float M00; public float M01; public float M10; public float M11; /// Bulk transpose matrices. public static unsafe void BulkTranspose(float* dest, float* src, int count) { for (int i = 0; i < count; ++i) { dest[0] = src[0]; dest[1] = src[2]; dest[2] = src[1]; dest[3] = src[3]; dest += 4; src += 4; } } /// Zero matrix. public static readonly Matrix2 ZERO = new Matrix2(0, 0, 0, 0); /// Identity matrix. public static readonly Matrix2 IDENTITY = new Matrix2( 1, 0, 0, 1); public override bool Equals(object obj) { return obj is Matrix2 other && Equals(other); } public override int GetHashCode() { unchecked { var hashCode = M00.GetHashCode(); hashCode = (hashCode * 397) ^ M01.GetHashCode(); hashCode = (hashCode * 397) ^ M10.GetHashCode(); hashCode = (hashCode * 397) ^ M11.GetHashCode(); return hashCode; } } }; }
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Orleans.Configuration; using Orleans.GrainDirectory; using Orleans.Runtime.ConsistentRing; using Orleans.Runtime.Counters; using Orleans.Runtime.GrainDirectory; using Orleans.Runtime.LogConsistency; using Orleans.Runtime.MembershipService; using Orleans.Runtime.Messaging; using Orleans.Runtime.MultiClusterNetwork; using Orleans.Runtime.Placement; using Orleans.Runtime.Providers; using Orleans.Runtime.ReminderService; using Orleans.Runtime.Scheduler; using Orleans.Runtime.Versions; using Orleans.Runtime.Versions.Compatibility; using Orleans.Runtime.Versions.Selector; using Orleans.Serialization; using Orleans.Streams; using Orleans.Streams.Core; using Orleans.Timers; using Orleans.Versions; using Orleans.Versions.Compatibility; using Orleans.Versions.Selector; using Orleans.Providers; using Orleans.Runtime; using Orleans.Transactions; using Orleans.LogConsistency; using Microsoft.Extensions.Logging; using Orleans.ApplicationParts; using Orleans.Runtime.Utilities; using System; using System.Collections.Generic; using Orleans.Metadata; using Orleans.Statistics; using Microsoft.Extensions.Options; using Orleans.Configuration.Validators; using Orleans.Runtime.Configuration; namespace Orleans.Hosting { internal static class DefaultSiloServices { internal static void AddDefaultServices(HostBuilderContext context, IServiceCollection services) { services.AddOptions(); // Options logging services.TryAddSingleton(typeof(IOptionFormatter<>), typeof(DefaultOptionsFormatter<>)); services.TryAddSingleton(typeof(IOptionFormatterResolver<>), typeof(DefaultOptionsFormatterResolver<>)); // Register system services. services.TryAddSingleton<ILocalSiloDetails, LocalSiloDetails>(); services.TryAddSingleton<ISiloHost, SiloWrapper>(); services.TryAddSingleton<SiloLifecycle>(); services.TryAddSingleton<ILifecycleParticipant<ISiloLifecycle>, SiloOptionsLogger>(); services.PostConfigure<SiloMessagingOptions>(options => { // // Assign environment specific defaults post configuration if user did not configured otherwise. // if (options.SiloSenderQueues==0) { options.SiloSenderQueues = Environment.ProcessorCount; } if (options.GatewaySenderQueues==0) { options.GatewaySenderQueues = Environment.ProcessorCount; } }); services.TryAddSingleton<TelemetryManager>(); services.TryAddFromExisting<ITelemetryProducer, TelemetryManager>(); services.TryAddSingleton<IAppEnvironmentStatistics, AppEnvironmentStatistics>(); services.TryAddSingleton<IHostEnvironmentStatistics, NoOpHostEnvironmentStatistics>(); services.TryAddSingleton<OverloadDetector>(); services.TryAddSingleton<ExecutorService>(); // queue balancer contructing related services.TryAddTransient<StaticClusterConfigDeploymentBalancer>(); services.TryAddTransient<DynamicClusterConfigDeploymentBalancer>(); services.TryAddTransient<ClusterConfigDeploymentLeaseBasedBalancer>(); services.TryAddTransient<ConsistentRingQueueBalancer>(); services.TryAddSingleton<IStreamSubscriptionHandleFactory, StreamSubscriptionHandlerFactory>(); services.TryAddSingleton<FallbackSystemTarget>(); services.TryAddSingleton<LifecycleSchedulingSystemTarget>(); services.AddLogging(); services.TryAddSingleton<ITimerRegistry, TimerRegistry>(); services.TryAddSingleton<IReminderRegistry, ReminderRegistry>(); services.TryAddSingleton<GrainRuntime>(); services.TryAddSingleton<IGrainRuntime, GrainRuntime>(); services.TryAddSingleton<IGrainCancellationTokenRuntime, GrainCancellationTokenRuntime>(); services.TryAddSingleton<OrleansTaskScheduler>(); services.TryAddSingleton<GrainFactory>(sp => sp.GetService<InsideRuntimeClient>().ConcreteGrainFactory); services.TryAddFromExisting<IGrainFactory, GrainFactory>(); services.TryAddFromExisting<IInternalGrainFactory, GrainFactory>(); services.TryAddFromExisting<IGrainReferenceConverter, GrainFactory>(); services.TryAddSingleton<IGrainReferenceRuntime, GrainReferenceRuntime>(); services.TryAddSingleton<TypeMetadataCache>(); services.TryAddSingleton<ActivationDirectory>(); services.TryAddSingleton<ActivationCollector>(); services.TryAddSingleton<LocalGrainDirectory>(); services.TryAddFromExisting<ILocalGrainDirectory, LocalGrainDirectory>(); services.TryAddSingleton(sp => sp.GetRequiredService<LocalGrainDirectory>().GsiActivationMaintainer); services.TryAddSingleton<SiloStatisticsManager>(); services.TryAddSingleton<GrainTypeManager>(); services.TryAddSingleton<MessageCenter>(); services.TryAddFromExisting<IMessageCenter, MessageCenter>(); services.TryAddFromExisting<ISiloMessageCenter, MessageCenter>(); services.TryAddSingleton(FactoryUtility.Create<MessageCenter, Gateway>); services.TryAddSingleton<Dispatcher>(sp => sp.GetRequiredService<Catalog>().Dispatcher); services.TryAddSingleton<InsideRuntimeClient>(); services.TryAddFromExisting<IRuntimeClient, InsideRuntimeClient>(); services.TryAddFromExisting<ISiloRuntimeClient, InsideRuntimeClient>(); services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, InsideRuntimeClient>(); services.TryAddSingleton<MultiClusterGossipChannelFactory>(); services.TryAddSingleton<MultiClusterOracle>(); services.TryAddSingleton<MultiClusterRegistrationStrategyManager>(); services.TryAddFromExisting<IMultiClusterOracle, MultiClusterOracle>(); services.TryAddSingleton<DeploymentLoadPublisher>(); services.TryAddSingleton<MembershipOracle>(); services.TryAddFromExisting<IMembershipOracle, MembershipOracle>(); services.TryAddFromExisting<ISiloStatusOracle, MembershipOracle>(); services.AddTransient<IConfigurationValidator, SiloClusteringValidator>(); services.TryAddSingleton<ClientObserverRegistrar>(); services.TryAddSingleton<SiloProviderRuntime>(); services.TryAddFromExisting<IStreamProviderRuntime, SiloProviderRuntime>(); services.TryAddFromExisting<IProviderRuntime, SiloProviderRuntime>(); services.TryAddSingleton<ImplicitStreamSubscriberTable>(); services.TryAddSingleton<MessageFactory>(); services.TryAddSingleton<IGrainRegistrar<GlobalSingleInstanceRegistration>, GlobalSingleInstanceRegistrar>(); services.TryAddSingleton<IGrainRegistrar<ClusterLocalRegistration>, ClusterLocalRegistrar>(); services.TryAddSingleton<RegistrarManager>(); services.TryAddSingleton<Factory<Grain, IMultiClusterRegistrationStrategy, ILogConsistencyProtocolServices>>(FactoryUtility.Create<Grain, IMultiClusterRegistrationStrategy, ProtocolServices>); services.TryAddSingleton(FactoryUtility.Create<GrainDirectoryPartition>); // Placement services.AddSingleton<IConfigurationValidator, ActivationCountBasedPlacementOptionsValidator>(); services.TryAddSingleton<PlacementDirectorsManager>(); services.TryAddSingleton<ClientObserversPlacementDirector>(); // Configure the default placement strategy. services.TryAddSingleton<PlacementStrategy, RandomPlacement>(); // Placement directors services.AddPlacementDirector<RandomPlacement, RandomPlacementDirector>(); services.AddPlacementDirector<PreferLocalPlacement, PreferLocalPlacementDirector>(); services.AddPlacementDirector<StatelessWorkerPlacement, StatelessWorkerDirector>(); services.AddPlacementDirector<ActivationCountBasedPlacement, ActivationCountPlacementDirector>(); services.AddPlacementDirector<HashBasedPlacement, HashBasedPlacementDirector>(); // Activation selectors services.AddSingletonKeyedService<Type, IActivationSelector, RandomPlacementDirector>(typeof(RandomPlacement)); services.AddSingletonKeyedService<Type, IActivationSelector, StatelessWorkerDirector>(typeof(StatelessWorkerPlacement)); // Versioning services.TryAddSingleton<VersionSelectorManager>(); services.TryAddSingleton<CachedVersionSelectorManager>(); // Version selector strategy services.TryAddSingleton<GrainVersionStore>(); services.AddFromExisting<IVersionStore, GrainVersionStore>(); services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, GrainVersionStore>(); services.AddSingletonNamedService<VersionSelectorStrategy, AllCompatibleVersions>(nameof(AllCompatibleVersions)); services.AddSingletonNamedService<VersionSelectorStrategy, LatestVersion>(nameof(LatestVersion)); services.AddSingletonNamedService<VersionSelectorStrategy, MinimumVersion>(nameof(MinimumVersion)); // Versions selectors services.AddSingletonKeyedService<Type, IVersionSelector, MinimumVersionSelector>(typeof(MinimumVersion)); services.AddSingletonKeyedService<Type, IVersionSelector, LatestVersionSelector>(typeof(LatestVersion)); services.AddSingletonKeyedService<Type, IVersionSelector, AllCompatibleVersionsSelector>(typeof(AllCompatibleVersions)); // Compatibility services.TryAddSingleton<CompatibilityDirectorManager>(); // Compatability strategy services.AddSingletonNamedService<CompatibilityStrategy, AllVersionsCompatible>(nameof(AllVersionsCompatible)); services.AddSingletonNamedService<CompatibilityStrategy, BackwardCompatible>(nameof(BackwardCompatible)); services.AddSingletonNamedService<CompatibilityStrategy, StrictVersionCompatible>(nameof(StrictVersionCompatible)); // Compatability directors services.AddSingletonKeyedService<Type, ICompatibilityDirector, BackwardCompatilityDirector>(typeof(BackwardCompatible)); services.AddSingletonKeyedService<Type, ICompatibilityDirector, AllVersionsCompatibilityDirector>(typeof(AllVersionsCompatible)); services.AddSingletonKeyedService<Type, ICompatibilityDirector, StrictVersionCompatibilityDirector>(typeof(StrictVersionCompatible)); services.TryAddSingleton<Factory<IGrainRuntime>>(sp => () => sp.GetRequiredService<IGrainRuntime>()); // Grain activation services.TryAddSingleton<Catalog>(); services.TryAddSingleton<GrainCreator>(); services.TryAddSingleton<IGrainActivator, DefaultGrainActivator>(); services.TryAddScoped<ActivationData.GrainActivationContextFactory>(); services.TryAddScoped<IGrainActivationContext>(sp => sp.GetRequiredService<ActivationData.GrainActivationContextFactory>().Context); services.TryAddSingleton<IStreamSubscriptionManagerAdmin>(sp => new StreamSubscriptionManagerAdmin(sp.GetRequiredService<IStreamProviderRuntime>())); services.TryAddSingleton<IConsistentRingProvider>( sp => { // TODO: make this not sux - jbragg var consistentRingOptions = sp.GetRequiredService<IOptions<ConsistentRingOptions>>().Value; var siloDetails = sp.GetRequiredService<ILocalSiloDetails>(); var loggerFactory = sp.GetRequiredService<ILoggerFactory>(); if (consistentRingOptions.UseVirtualBucketsConsistentRing) { return new VirtualBucketsRingProvider(siloDetails.SiloAddress, loggerFactory, consistentRingOptions.NumVirtualBucketsConsistentRing); } return new ConsistentRingProvider(siloDetails.SiloAddress, loggerFactory); }); services.TryAddSingleton(typeof(IKeyedServiceCollection<,>), typeof(KeyedServiceCollection<,>)); // Serialization services.TryAddSingleton<SerializationManager>(); services.TryAddSingleton<ITypeResolver, CachedTypeResolver>(); services.TryAddSingleton<IFieldUtils, FieldUtils>(); services.AddSingleton<BinaryFormatterSerializer>(); services.AddSingleton<BinaryFormatterISerializableSerializer>(); services.AddFromExisting<IKeyedSerializer, BinaryFormatterISerializableSerializer>(); services.AddSingleton<ILBasedSerializer>(); services.AddFromExisting<IKeyedSerializer, ILBasedSerializer>(); // Transactions services.TryAddSingleton<ITransactionAgent, TransactionAgent>(); services.TryAddSingleton<Factory<ITransactionAgent>>(sp => () => sp.GetRequiredService<ITransactionAgent>()); services.TryAddSingleton<ITransactionManagerService, DisabledTransactionManagerService>(); // Application Parts var applicationPartManager = context.GetApplicationPartManager(); services.TryAddSingleton<IApplicationPartManager>(applicationPartManager); applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(RuntimeVersion).Assembly) {IsFrameworkAssembly = true}); applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(Silo).Assembly) {IsFrameworkAssembly = true}); applicationPartManager.AddFeatureProvider(new BuiltInTypesSerializationFeaturePopulator()); applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<GrainInterfaceFeature>()); applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<GrainClassFeature>()); applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<SerializerFeature>()); services.AddTransient<IConfigurationValidator, ApplicationPartValidator>(); //Add default option formatter if none is configured, for options which are required to be configured services.ConfigureFormatter<SiloOptions>(); services.ConfigureFormatter<ProcessExitHandlingOptions>(); services.ConfigureFormatter<SchedulingOptions>(); services.ConfigureFormatter<PerformanceTuningOptions>(); services.ConfigureFormatter<SerializationProviderOptions>(); services.ConfigureFormatter<NetworkingOptions>(); services.ConfigureFormatter<SiloMessagingOptions>(); services.ConfigureFormatter<TypeManagementOptions>(); services.ConfigureFormatter<ClusterMembershipOptions>(); services.ConfigureFormatter<GrainDirectoryOptions>(); services.ConfigureFormatter<ActivationCountBasedPlacementOptions>(); services.ConfigureFormatter<GrainCollectionOptions>(); services.ConfigureFormatter<GrainVersioningOptions>(); services.ConfigureFormatter<ConsistentRingOptions>(); services.ConfigureFormatter<MultiClusterOptions>(); services.ConfigureFormatter<SiloStatisticsOptions>(); services.ConfigureFormatter<GrainServiceOptions>(); services.ConfigureFormatter<TelemetryOptions>(); services.ConfigureFormatter<LoadSheddingOptions>(); services.ConfigureFormatter<EndpointOptions>(); services.AddTransient<IConfigurationValidator, EndpointOptionsValidator>(); } } }
// 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.Immutable; using System.Diagnostics; using System.Text; namespace System.Reflection.Metadata.Decoding.Tests { internal class DisassemblingGenericContext { public DisassemblingGenericContext(ImmutableArray<string> typeParameters, ImmutableArray<string> methodParameters) { MethodParameters = methodParameters; TypeParameters = typeParameters; } public ImmutableArray<string> MethodParameters { get; } public ImmutableArray<string> TypeParameters { get; } } // Test implementation of ISignatureTypeProvider<TType, TGenericContext> that uses strings in ilasm syntax as TType. // A real provider in any sort of perf constraints would not want to allocate strings freely like this, but it keeps test code simple. internal class DisassemblingTypeProvider : ISignatureTypeProvider<string, DisassemblingGenericContext> { public virtual string GetPrimitiveType(PrimitiveTypeCode typeCode) { switch (typeCode) { case PrimitiveTypeCode.Boolean: return "bool"; case PrimitiveTypeCode.Byte: return "uint8"; case PrimitiveTypeCode.Char: return "char"; case PrimitiveTypeCode.Double: return "float64"; case PrimitiveTypeCode.Int16: return "int16"; case PrimitiveTypeCode.Int32: return "int32"; case PrimitiveTypeCode.Int64: return "int64"; case PrimitiveTypeCode.IntPtr: return "native int"; case PrimitiveTypeCode.Object: return "object"; case PrimitiveTypeCode.SByte: return "int8"; case PrimitiveTypeCode.Single: return "float32"; case PrimitiveTypeCode.String: return "string"; case PrimitiveTypeCode.TypedReference: return "typedref"; case PrimitiveTypeCode.UInt16: return "uint16"; case PrimitiveTypeCode.UInt32: return "uint32"; case PrimitiveTypeCode.UInt64: return "uint64"; case PrimitiveTypeCode.UIntPtr: return "native uint"; case PrimitiveTypeCode.Void: return "void"; default: Debug.Assert(false); throw new ArgumentOutOfRangeException(nameof(typeCode)); } } public virtual string GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind = 0) { TypeDefinition definition = reader.GetTypeDefinition(handle); string name = definition.Namespace.IsNil ? reader.GetString(definition.Name) : reader.GetString(definition.Namespace) + "." + reader.GetString(definition.Name); if (definition.Attributes.IsNested()) { TypeDefinitionHandle declaringTypeHandle = definition.GetDeclaringType(); return GetTypeFromDefinition(reader, declaringTypeHandle, 0) + "/" + name; } return name; } public virtual string GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind = 0) { TypeReference reference = reader.GetTypeReference(handle); Handle scope = reference.ResolutionScope; string name = reference.Namespace.IsNil ? reader.GetString(reference.Name) : reader.GetString(reference.Namespace) + "." + reader.GetString(reference.Name); switch (scope.Kind) { case HandleKind.ModuleReference: return "[.module " + reader.GetString(reader.GetModuleReference((ModuleReferenceHandle)scope).Name) + "]" + name; case HandleKind.AssemblyReference: var assemblyReferenceHandle = (AssemblyReferenceHandle)scope; var assemblyReference = reader.GetAssemblyReference(assemblyReferenceHandle); return "[" + reader.GetString(assemblyReference.Name) + "]" + name; case HandleKind.TypeReference: return GetTypeFromReference(reader, (TypeReferenceHandle)scope) + "/" + name; default: // rare cases: ModuleDefinition means search within defs of current module (used by WinMDs for projections) // nil means search exported types of same module (haven't seen this in practice). For the test // purposes here, it's sufficient to format both like defs. Debug.Assert(scope == Handle.ModuleDefinition || scope.IsNil); return name; } } public virtual string GetTypeFromSpecification(MetadataReader reader, DisassemblingGenericContext genericContext, TypeSpecificationHandle handle, byte rawTypeKind = 0) { return reader.GetTypeSpecification(handle).DecodeSignature(this, genericContext); } public virtual string GetSZArrayType(string elementType) { return elementType + "[]"; } public virtual string GetPointerType(string elementType) { return elementType + "*"; } public virtual string GetByReferenceType(string elementType) { return elementType + "&"; } public virtual string GetGenericMethodParameter(DisassemblingGenericContext genericContext, int index) { return "!!" + genericContext.MethodParameters[index]; } public virtual string GetGenericTypeParameter(DisassemblingGenericContext genericContext, int index) { return "!" + genericContext.TypeParameters[index]; } public virtual string GetPinnedType(string elementType) { return elementType + " pinned"; } public virtual string GetGenericInstantiation(string genericType, ImmutableArray<string> typeArguments) { return genericType + "<" + string.Join(",", typeArguments) + ">"; } public virtual string GetArrayType(string elementType, ArrayShape shape) { var builder = new StringBuilder(); builder.Append(elementType); builder.Append('['); for (int i = 0; i < shape.Rank; i++) { int lowerBound = 0; if (i < shape.LowerBounds.Length) { lowerBound = shape.LowerBounds[i]; builder.Append(lowerBound); } builder.Append("..."); if (i < shape.Sizes.Length) { builder.Append(lowerBound + shape.Sizes[i] - 1); } if (i < shape.Rank - 1) { builder.Append(','); } } builder.Append(']'); return builder.ToString(); } public virtual string GetTypeFromHandle(MetadataReader reader, DisassemblingGenericContext genericContext, EntityHandle handle) { switch (handle.Kind) { case HandleKind.TypeDefinition: return GetTypeFromDefinition(reader, (TypeDefinitionHandle)handle); case HandleKind.TypeReference: return GetTypeFromReference(reader, (TypeReferenceHandle)handle); case HandleKind.TypeSpecification: return GetTypeFromSpecification(reader, genericContext, (TypeSpecificationHandle)handle); default: throw new ArgumentOutOfRangeException(nameof(handle)); } } public virtual string GetModifiedType(string modifierType, string unmodifiedType, bool isRequired) { return unmodifiedType + (isRequired ? " modreq(" : " modopt(") + modifierType + ")"; } public virtual string GetFunctionPointerType(MethodSignature<string> signature) { ImmutableArray<string> parameterTypes = signature.ParameterTypes; int requiredParameterCount = signature.RequiredParameterCount; var builder = new StringBuilder(); builder.Append("method "); builder.Append(signature.ReturnType); builder.Append(" *("); int i; for (i = 0; i < requiredParameterCount; i++) { builder.Append(parameterTypes[i]); if (i < parameterTypes.Length - 1) { builder.Append(", "); } } if (i < parameterTypes.Length) { builder.Append("..., "); for (; i < parameterTypes.Length; i++) { builder.Append(parameterTypes[i]); if (i < parameterTypes.Length - 1) { builder.Append(", "); } } } builder.Append(')'); return builder.ToString(); } } }
using System; using System.Runtime.InteropServices; // ReSharper disable FieldCanBeMadeReadOnly.Global // ReSharper disable MemberCanBePrivate.Global // ReSharper disable FieldCanBeMadeReadOnly.Local namespace Avalonia.LinuxFramebuffer.Output { public enum DrmModeConnection { DRM_MODE_CONNECTED = 1, DRM_MODE_DISCONNECTED = 2, DRM_MODE_UNKNOWNCONNECTION = 3 } public enum DrmModeSubPixel{ DRM_MODE_SUBPIXEL_UNKNOWN = 1, DRM_MODE_SUBPIXEL_HORIZONTAL_RGB = 2, DRM_MODE_SUBPIXEL_HORIZONTAL_BGR = 3, DRM_MODE_SUBPIXEL_VERTICAL_RGB = 4, DRM_MODE_SUBPIXEL_VERTICAL_BGR = 5, DRM_MODE_SUBPIXEL_NONE = 6 } static unsafe class LibDrm { private const string libdrm = "libdrm.so.2"; private const string libgbm = "libgbm.so.1"; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void DrmEventVBlankHandlerDelegate(int fd, uint sequence, uint tv_sec, uint tv_usec, void* user_data); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void DrmEventPageFlipHandlerDelegate(int fd, uint sequence, uint tv_sec, uint tv_usec, void* user_data); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate IntPtr DrmEventPageFlipHandler2Delegate(int fd, uint sequence, uint tv_sec, uint tv_usec, uint crtc_id, void* user_data); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void DrmEventSequenceHandlerDelegate(int fd, ulong sequence, ulong ns, ulong user_data); [StructLayout(LayoutKind.Sequential)] public struct DrmEventContext { public int version; //4 public IntPtr vblank_handler; public IntPtr page_flip_handler; public IntPtr page_flip_handler2; public IntPtr sequence_handler; } [StructLayout(LayoutKind.Sequential)] public struct drmModeRes { public int count_fbs; public uint *fbs; public int count_crtcs; public uint *crtcs; public int count_connectors; public uint *connectors; public int count_encoders; public uint *encoders; uint min_width, max_width; uint min_height, max_height; } [Flags] public enum DrmModeType { DRM_MODE_TYPE_BUILTIN = (1 << 0), DRM_MODE_TYPE_CLOCK_C = ((1 << 1) | DRM_MODE_TYPE_BUILTIN), DRM_MODE_TYPE_CRTC_C = ((1 << 2) | DRM_MODE_TYPE_BUILTIN), DRM_MODE_TYPE_PREFERRED = (1 << 3), DRM_MODE_TYPE_DEFAULT = (1 << 4), DRM_MODE_TYPE_USERDEF = (1 << 5), DRM_MODE_TYPE_DRIVER = (1 << 6) } [StructLayout(LayoutKind.Sequential)] public struct drmModeModeInfo { public uint clock; public ushort hdisplay, hsync_start, hsync_end, htotal, hskew; public ushort vdisplay, vsync_start, vsync_end, vtotal, vscan; public uint vrefresh; public uint flags; public DrmModeType type; public fixed byte name[32]; public PixelSize Resolution => new PixelSize(hdisplay, vdisplay); } [StructLayout(LayoutKind.Sequential)] public struct drmModeConnector { public uint connector_id; public uint encoder_id; // Encoder currently connected to public uint connector_type; public uint connector_type_id; public DrmModeConnection connection; public uint mmWidth, mmHeight; // HxW in millimeters public DrmModeSubPixel subpixel; public int count_modes; public drmModeModeInfo* modes; public int count_props; public uint *props; // List of property ids public ulong *prop_values; // List of property values public int count_encoders; public uint *encoders; //List of encoder ids } [StructLayout(LayoutKind.Sequential)] public struct drmModeEncoder { public uint encoder_id; public uint encoder_type; public uint crtc_id; public uint possible_crtcs; public uint possible_clones; } [StructLayout(LayoutKind.Sequential)] public struct drmModeCrtc { public uint crtc_id; public uint buffer_id; // FB id to connect to 0 = disconnect public uint x, y; // Position on the framebuffer public uint width, height; public int mode_valid; public drmModeModeInfo mode; public int gamma_size; // Number of gamma stops } [DllImport(libdrm, SetLastError = true)] public static extern drmModeRes* drmModeGetResources(int fd); [DllImport(libdrm, SetLastError = true)] public static extern void drmModeFreeResources(drmModeRes* res); [DllImport(libdrm, SetLastError = true)] public static extern drmModeConnector* drmModeGetConnector(int fd, uint connector); [DllImport(libdrm, SetLastError = true)] public static extern void drmModeFreeConnector(drmModeConnector* res); [DllImport(libdrm, SetLastError = true)] public static extern drmModeEncoder* drmModeGetEncoder(int fd, uint id); [DllImport(libdrm, SetLastError = true)] public static extern void drmModeFreeEncoder(drmModeEncoder* enc); [DllImport(libdrm, SetLastError = true)] public static extern drmModeCrtc* drmModeGetCrtc(int fd, uint id); [DllImport(libdrm, SetLastError = true)] public static extern void drmModeFreeCrtc(drmModeCrtc* enc); [DllImport(libdrm, SetLastError = true)] public static extern int drmModeAddFB(int fd, uint width, uint height, byte depth, byte bpp, uint pitch, uint bo_handle, out uint buf_id); [DllImport(libdrm, SetLastError = true)] public static extern int drmModeAddFB2(int fd, uint width, uint height, uint pixel_format, uint[] bo_handles, uint[] pitches, uint[] offsets, out uint buf_id, uint flags); [DllImport(libdrm, SetLastError = true)] public static extern int drmModeSetCrtc(int fd, uint crtcId, uint bufferId, uint x, uint y, uint *connectors, int count, drmModeModeInfo* mode); [DllImport(libdrm, SetLastError = true)] public static extern void drmModeRmFB(int fd, int id); [Flags] public enum DrmModePageFlip { Event = 1, Async = 2, Absolute = 4, Relative = 8, } [DllImport(libdrm, SetLastError = true)] public static extern void drmModePageFlip(int fd, uint crtc_id, uint fb_id, DrmModePageFlip flags, void *user_data); [DllImport(libdrm, SetLastError = true)] public static extern void drmHandleEvent(int fd, DrmEventContext* context); [DllImport(libgbm, SetLastError = true)] public static extern IntPtr gbm_create_device(int fd); [Flags] public enum GbmBoFlags { /** * Buffer is going to be presented to the screen using an API such as KMS */ GBM_BO_USE_SCANOUT = (1 << 0), /** * Buffer is going to be used as cursor */ GBM_BO_USE_CURSOR = (1 << 1), /** * Deprecated */ GBM_BO_USE_CURSOR_64X64 = GBM_BO_USE_CURSOR, /** * Buffer is to be used for rendering - for example it is going to be used * as the storage for a color buffer */ GBM_BO_USE_RENDERING = (1 << 2), /** * Buffer can be used for gbm_bo_write. This is guaranteed to work * with GBM_BO_USE_CURSOR, but may not work for other combinations. */ GBM_BO_USE_WRITE = (1 << 3), /** * Buffer is linear, i.e. not tiled. */ GBM_BO_USE_LINEAR = (1 << 4), }; [DllImport(libgbm, SetLastError = true)] public static extern IntPtr gbm_surface_create(IntPtr device, int width, int height, uint format, GbmBoFlags flags); [DllImport(libgbm, SetLastError = true)] public static extern IntPtr gbm_surface_lock_front_buffer(IntPtr surface); [DllImport(libgbm, SetLastError = true)] public static extern int gbm_surface_release_buffer(IntPtr surface, IntPtr bo); [DllImport(libgbm, SetLastError = true)] public static extern IntPtr gbm_bo_get_user_data(IntPtr surface); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void GbmBoUserDataDestroyCallbackDelegate(IntPtr bo, IntPtr data); [DllImport(libgbm, SetLastError = true)] public static extern IntPtr gbm_bo_set_user_data(IntPtr bo, IntPtr userData, GbmBoUserDataDestroyCallbackDelegate onFree); [DllImport(libgbm, SetLastError = true)] public static extern uint gbm_bo_get_width(IntPtr bo); [DllImport(libgbm, SetLastError = true)] public static extern uint gbm_bo_get_height(IntPtr bo); [DllImport(libgbm, SetLastError = true)] public static extern uint gbm_bo_get_stride(IntPtr bo); [DllImport(libgbm, SetLastError = true)] public static extern uint gbm_bo_get_format(IntPtr bo); [StructLayout(LayoutKind.Explicit)] public struct GbmBoHandle { [FieldOffset(0)] public void *ptr; [FieldOffset(0)] public int s32; [FieldOffset(0)] public uint u32; [FieldOffset(0)] public long s64; [FieldOffset(0)] public ulong u64; } [DllImport(libgbm, SetLastError = true)] public static extern GbmBoHandle gbm_bo_get_handle(IntPtr bo); public static class GbmColorFormats { public static uint FourCC(char a, char b, char c, char d) => (uint)a | ((uint)b) << 8 | ((uint)c) << 16 | ((uint)d) << 24; public static uint GBM_FORMAT_XRGB8888 { get; } = FourCC('X', 'R', '2', '4'); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using FluentAssertions; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.TestFramework; using Microsoft.DotNet.Tools.Test.Utilities; using NuGet.Frameworks; using NuGet.ProjectModel; using NuGet.Versioning; using Xunit; using Microsoft.DotNet.Tools.Tests.Utilities; namespace Microsoft.DotNet.Tests { public class GivenAProjectToolsCommandResolver : TestBase { private static readonly NuGetFramework s_toolPackageFramework = NuGetFrameworks.NetCoreApp21; private const string TestProjectName = "AppWithToolDependency"; [Fact] public void ItReturnsNullWhenCommandNameIsNull() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = null, CommandArguments = new string[] { "" }, ProjectDirectory = "/some/directory" }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void ItReturnsNullWhenProjectDirectoryIsNull() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "command", CommandArguments = new string[] { "" }, ProjectDirectory = null }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void ItReturnsNullWhenProjectDirectoryDoesNotContainAProjectFile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var projectDirectory = TestAssets.CreateTestDirectory(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "command", CommandArguments = new string[] { "" }, ProjectDirectory = projectDirectory.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void ItReturnsNullWhenCommandNameDoesNotExistInProjectTools() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "nonexistent-command", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void ItReturnsACommandSpecWithDOTNETAsFileNameAndCommandNameInArgsWhenCommandNameExistsInProjectTools() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandFile = Path.GetFileNameWithoutExtension(result.Path); commandFile.Should().Be("dotnet"); result.Args.Should().Contain(commandResolverArguments.CommandName); } [Fact] public void ItEscapesCommandArgumentsWhenReturningACommandSpec() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = new[] { "arg with space" }, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull("Because the command is a project tool dependency"); result.Args.Should().Contain("\"arg with space\""); } [Fact] public void ItReturnsACommandSpecWithArgsContainingCommandPathWhenReturningACommandSpecAndCommandArgumentsAreNull() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandPath = result.Args.Trim('"'); commandPath.Should().Contain("dotnet-portable.dll"); } [Fact] public void ItReturnsACommandSpecWithArgsContainingCommandPathWhenInvokingAToolReferencedWithADifferentCasing() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-prefercliruntime", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandPath = result.Args.Trim('"'); commandPath.Should().Contain("dotnet-prefercliruntime.dll"); } [Fact] public void ItWritesADepsJsonFileNextToTheLockfile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var repoDirectoriesProvider = new RepoDirectoriesProvider(); var nugetPackagesRoot = repoDirectoriesProvider.NugetPackages; var toolPathCalculator = new ToolPathCalculator(nugetPackagesRoot); var lockFilePath = toolPathCalculator.GetLockFilePath( "dotnet-portable", new NuGetVersion("1.0.0"), s_toolPackageFramework); var directory = Path.GetDirectoryName(lockFilePath); var depsJsonFile = Directory .EnumerateFiles(directory) .FirstOrDefault(p => Path.GetFileName(p).EndsWith(FileNameSuffixes.DepsJson)); if (depsJsonFile != null) { File.Delete(depsJsonFile); } var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); new DirectoryInfo(directory) .Should().HaveFilesMatching("*.deps.json", SearchOption.TopDirectoryOnly); } [Fact] public void GenerateDepsJsonMethodDoesntOverwriteWhenDepsFileAlreadyExists() { var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var repoDirectoriesProvider = new RepoDirectoriesProvider(); var nugetPackagesRoot = repoDirectoriesProvider.NugetPackages; var toolPathCalculator = new ToolPathCalculator(nugetPackagesRoot); var lockFilePath = toolPathCalculator.GetLockFilePath( "dotnet-portable", new NuGetVersion("1.0.0"), s_toolPackageFramework); var lockFile = new LockFileFormat().Read(lockFilePath); // NOTE: We must not use the real deps.json path here as it will interfere with tests running in parallel. var depsJsonFile = Path.GetTempFileName(); File.WriteAllText(depsJsonFile, "temp"); var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); projectToolsCommandResolver.GenerateDepsJsonFile( lockFile, s_toolPackageFramework, depsJsonFile, new SingleProjectInfo("dotnet-portable", "1.0.0", Enumerable.Empty<ResourceAssemblyInfo>()), GetToolDepsJsonGeneratorProject()); File.ReadAllText(depsJsonFile).Should().Be("temp"); File.Delete(depsJsonFile); } [Fact] public void ItAddsFxVersionAsAParamWhenTheToolHasThePrefercliruntimeFile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get("MSBuildTestApp") .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-prefercliruntime", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().Contain("--fx-version 2.1.0"); } [Fact] public void ItDoesNotAddFxVersionAsAParamWhenTheToolDoesNotHaveThePrefercliruntimeFile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().NotContain("--fx-version"); } [Fact] public void ItFindsToolsLocatedInTheNuGetFallbackFolder() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get("AppWithFallbackFolderToolDependency") .CreateInstance() .WithSourceFiles() .WithNuGetConfig(new RepoDirectoriesProvider().TestPackages); var testProjectDirectory = testInstance.Root.FullName; var fallbackFolder = Path.Combine(testProjectDirectory, "fallbackFolder"); PopulateFallbackFolder(testProjectDirectory, fallbackFolder); var nugetConfig = UseNuGetConfigWithFallbackFolder(testInstance, fallbackFolder); new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute($"--configfile {nugetConfig}") .Should() .Pass(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-fallbackfoldertool", CommandArguments = null, ProjectDirectory = testProjectDirectory }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandPath = result.Args.Trim('"'); commandPath.Should().Contain(Path.Combine( fallbackFolder, "dotnet-fallbackfoldertool", "1.0.0", "lib", "netcoreapp2.1", "dotnet-fallbackfoldertool.dll")); } [Fact] public void ItShowsAnErrorWhenTheToolDllIsNotFound() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get("AppWithFallbackFolderToolDependency") .CreateInstance() .WithSourceFiles() .WithNuGetConfig(new RepoDirectoriesProvider().TestPackages); var testProjectDirectory = testInstance.Root.FullName; var fallbackFolder = Path.Combine(testProjectDirectory, "fallbackFolder"); PopulateFallbackFolder(testProjectDirectory, fallbackFolder); var nugetConfig = UseNuGetConfigWithFallbackFolder(testInstance, fallbackFolder); new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute($"--configfile {nugetConfig}") .Should() .Pass(); Directory.Delete(Path.Combine(fallbackFolder, "dotnet-fallbackfoldertool"), true); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-fallbackfoldertool", CommandArguments = null, ProjectDirectory = testProjectDirectory }; Action action = () => projectToolsCommandResolver.Resolve(commandResolverArguments); action.ShouldThrow<GracefulException>().WithMessage( string.Format(LocalizableStrings.CommandAssembliesNotFound, "dotnet-fallbackfoldertool")); } private void PopulateFallbackFolder(string testProjectDirectory, string fallbackFolder) { var nugetConfigPath = Path.Combine(testProjectDirectory, "NuGet.Config"); new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute($"--configfile {nugetConfigPath} --packages {fallbackFolder}") .Should() .Pass(); Directory.Delete(Path.Combine(fallbackFolder, ".tools"), true); } private string UseNuGetConfigWithFallbackFolder(TestAssetInstance testInstance, string fallbackFolder) { var nugetConfig = testInstance.Root.GetFile("NuGet.Config").FullName; File.WriteAllText( nugetConfig, $@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <fallbackPackageFolders> <add key=""MachineWide"" value=""{fallbackFolder}""/> </fallbackPackageFolders> </configuration> "); return nugetConfig; } private ProjectToolsCommandResolver SetupProjectToolsCommandResolver() { Environment.SetEnvironmentVariable( Constants.MSBUILD_EXE_PATH, Path.Combine(new RepoDirectoriesProvider().Stage2Sdk, "MSBuild.dll")); var packagedCommandSpecFactory = new PackagedCommandSpecFactoryWithCliRuntime(); var projectToolsCommandResolver = new ProjectToolsCommandResolver(packagedCommandSpecFactory, new EnvironmentProvider()); return projectToolsCommandResolver; } private string GetToolDepsJsonGeneratorProject() { // When using the product, the ToolDepsJsonGeneratorProject property is used to get this path, but for testing // we'll hard code the path inside the SDK since we don't have a project to evaluate here return Path.Combine(new RepoDirectoriesProvider().Stage2Sdk, "Sdks", "Microsoft.NET.Sdk", "build", "GenerateDeps", "GenerateDeps.proj"); } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using OttoMail.Models; namespace OttoMail.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20160501234141_AddEmailToApplicationDbContext")] partial class AddEmailToApplicationDbContext { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("OttoMail.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("OttoMail.Models.Email", b => { b.Property<int>("EmailId") .ValueGeneratedOnAdd(); b.Property<string>("Body"); b.Property<bool>("Checked"); b.Property<DateTime>("Date"); b.Property<bool>("Read"); b.Property<string>("Sender"); b.Property<string>("Subject"); b.Property<string>("UserId"); b.HasKey("EmailId"); b.HasAnnotation("Relational:TableName", "Emails"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("OttoMail.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("OttoMail.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("OttoMail.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("OttoMail.Models.Email", b => { b.HasOne("OttoMail.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
// 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.Runtime.CompilerServices; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)' namespace System { /// <summary> /// ReadOnlySpan represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed /// or native memory, or to memory allocated on the stack. It is type- and memory-safe. /// </summary> public struct ReadOnlySpan<T> { /// <summary>A byref or a native ptr.</summary> private readonly ByReference<T> _pointer; /// <summary>The number of elements this ReadOnlySpan contains.</summary> private readonly int _length; /// <summary> /// Creates a new read-only span over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); _pointer = new ByReference<T>(ref JitHelpers.GetArrayData(array)); _length = array.Length; } /// <summary> /// Creates a new read-only span over the portion of the target array beginning /// at 'start' index and covering the remainder of the array. /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the read-only span.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[] array, int start) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if ((uint)start > (uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.Add(ref JitHelpers.GetArrayData(array), start)); _length = array.Length - start; } /// <summary> /// Creates a new read-only span over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the read-only span.</param> /// <param name="length">The number of items in the read-only span.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[] array, int start, int length) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.Add(ref JitHelpers.GetArrayData(array), start)); _length = length; } /// <summary> /// Creates a new read-only span over the target unmanaged buffer. Clearly this /// is quite dangerous, because we are creating arbitrarily typed T's /// out of a void*-typed block of memory. And the length is not checked. /// But if this creation is correct, then all subsequent uses are correct. /// </summary> /// <param name="pointer">An unmanaged pointer to memory.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe ReadOnlySpan(void* pointer, int length) { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer)); _length = length; } /// <summary> /// Create a new read-only span over a portion of a regular managed object. This can be useful /// if part of a managed object represents a "fixed array." This is dangerous because /// "length" is not checked, nor is the fact that "rawPointer" actually lies within the object. /// </summary> /// <param name="obj">The managed object that contains the data to span over.</param> /// <param name="objectData">A reference to data within that object.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> /// <exception cref="System.ArgumentNullException"> /// Thrown when the specified object is null. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length) { if (obj == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); return new ReadOnlySpan<T>(ref objectData, length); } // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlySpan(ref T ptr, int length) { Debug.Assert(length >= 0); _pointer = new ByReference<T>(ref ptr); _length = length; } /// <summary> /// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element /// would have been stored. Such a reference can be used for pinning but must never be dereferenced. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T DangerousGetPinnableReference() { return ref _pointer.Value; } /// <summary> /// The number of items in the read-only span. /// </summary> public int Length => _length; /// <summary> /// Returns true if Length is 0. /// </summary> public bool IsEmpty => _length == 0; /// <summary> /// Returns the specified element of the read-only span. /// </summary> /// <param name="index"></param> /// <returns></returns> /// <exception cref="System.IndexOutOfRangeException"> /// Thrown when index less than 0 or index greater than or equal to Length /// </exception> public T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) ThrowHelper.ThrowIndexOutOfRangeException(); return Unsafe.Add(ref _pointer.Value, index); } } /// <summary> /// Copies the contents of this read-only span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// /// <param name="destination">The span to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination Span is shorter than the source Span. /// </exception> /// </summary> public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) ThrowHelper.ThrowArgumentException_DestinationTooShort(); } /// Copies the contents of this read-only span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <returns>If the destination span is shorter than the source span, this method /// return false and no data is written to the destination.</returns> /// <param name="destination">The span to copy items into.</param> public bool TryCopyTo(Span<T> destination) { if ((uint)_length > (uint)destination.Length) return false; SpanHelper.CopyTo<T>(ref destination.DangerousGetPinnableReference(), ref _pointer.Value, _length); return true; } /// <summary> /// Returns true if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value); } /// <summary> /// Returns false if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) => !(left == right); /// <summary> /// This method is not supported as spans cannot be boxed. To compare two spans, use operator==. /// <exception cref="System.NotSupportedException"> /// Always thrown by this method. /// </exception> /// </summary> [Obsolete("Equals() on Span will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { ThrowHelper.ThrowNotSupportedException_CannotCallEqualsOnSpan(); // Prevent compiler error CS0161: 'Span<T>.Equals(object)': not all code paths return a value return default(bool); } /// <summary> /// This method is not supported as spans cannot be boxed. /// <exception cref="System.NotSupportedException"> /// Always thrown by this method. /// </exception> /// </summary> [Obsolete("GetHashCode() on Span will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { ThrowHelper.ThrowNotSupportedException_CannotCallGetHashCodeOnSpan(); // Prevent compiler error CS0161: 'Span<T>.GetHashCode()': not all code paths return a value return default(int); } /// <summary> /// Defines an implicit conversion of an array to a <see cref="ReadOnlySpan{T}"/> /// </summary> public static implicit operator ReadOnlySpan<T>(T[] array) => new ReadOnlySpan<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlySpan{T}"/> /// </summary> public static implicit operator ReadOnlySpan<T>(ArraySegment<T> arraySegment) => new ReadOnlySpan<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count); /// <summary> /// Forms a slice out of the given read-only span, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start) { if ((uint)start > (uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start); } /// <summary> /// Forms a slice out of the given read-only span, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), length); } /// <summary> /// Copies the contents of this read-only span into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> public T[] ToArray() { if (_length == 0) return Array.Empty<T>(); var destination = new T[_length]; SpanHelper.CopyTo<T>(ref JitHelpers.GetArrayData(destination), ref _pointer.Value, _length); return destination; } /// <summary> /// Returns a 0-length read-only span whose base is the null pointer. /// </summary> public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<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; using System.Collections; using System.Collections.Specialized; using System.Threading; using System.Diagnostics; using System.Security; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; namespace System.Runtime.Caching { internal sealed class MemoryCacheStore : IDisposable { private const int INSERT_BLOCK_WAIT = 10000; private const int MAX_COUNT = int.MaxValue / 2; private Hashtable _entries; private object _entriesLock; private CacheExpires _expires; private CacheUsage _usage; private int _disposed; private ManualResetEvent _insertBlock; private volatile bool _useInsertBlock; private MemoryCache _cache; private PerfCounters _perfCounters; internal MemoryCacheStore(MemoryCache cache, PerfCounters perfCounters) { _cache = cache; _perfCounters = perfCounters; _entries = new Hashtable(new MemoryCacheEqualityComparer()); _entriesLock = new object(); _expires = new CacheExpires(this); _usage = new CacheUsage(this); InitDisposableMembers(); } // private members private void AddToCache(MemoryCacheEntry entry) { // add outside of lock if (entry == null) { return; } if (entry.HasExpiration()) { _expires.Add(entry); } if (entry.HasUsage() && (!entry.HasExpiration() || entry.UtcAbsExp - DateTime.UtcNow >= CacheUsage.MIN_LIFETIME_FOR_USAGE)) { _usage.Add(entry); } // One last sanity check to be sure we didn't fall victim to an Add concurrency if (!entry.CompareExchangeState(EntryState.AddedToCache, EntryState.AddingToCache)) { if (entry.InExpires()) { _expires.Remove(entry); } if (entry.InUsage()) { _usage.Remove(entry); } } entry.CallNotifyOnChanged(); if (_perfCounters != null) { _perfCounters.Increment(PerfCounterName.Entries); _perfCounters.Increment(PerfCounterName.Turnover); } } private void InitDisposableMembers() { _insertBlock = new ManualResetEvent(true); _expires.EnableExpirationTimer(true); } private void RemoveFromCache(MemoryCacheEntry entry, CacheEntryRemovedReason reason, bool delayRelease = false) { // release outside of lock if (entry != null) { if (entry.InExpires()) { _expires.Remove(entry); } if (entry.InUsage()) { _usage.Remove(entry); } Dbg.Assert(entry.State == EntryState.RemovingFromCache, "entry.State = EntryState.RemovingFromCache"); entry.State = EntryState.RemovedFromCache; if (!delayRelease) { entry.Release(_cache, reason); } if (_perfCounters != null) { _perfCounters.Decrement(PerfCounterName.Entries); _perfCounters.Increment(PerfCounterName.Turnover); } } } // 'updatePerfCounters' defaults to true since this method is called by all Get() operations // to update both the performance counters and the sliding expiration. Callers that perform // nested sliding expiration updates (like a MemoryCacheEntry touching its update sentinel) // can pass false to prevent these from unintentionally showing up in the perf counters. internal void UpdateExpAndUsage(MemoryCacheEntry entry, bool updatePerfCounters = true) { if (entry != null) { if (entry.InUsage() || entry.SlidingExp > TimeSpan.Zero) { DateTime utcNow = DateTime.UtcNow; entry.UpdateSlidingExp(utcNow, _expires); entry.UpdateUsage(utcNow, _usage); } // If this entry has an update sentinel, the sliding expiration is actually associated // with that sentinel, not with this entry. We need to update the sentinel's sliding expiration to // keep the sentinel from expiring, which in turn would force a removal of this entry from the cache. entry.UpdateSlidingExpForUpdateSentinel(); if (updatePerfCounters && _perfCounters != null) { _perfCounters.Increment(PerfCounterName.Hits); _perfCounters.Increment(PerfCounterName.HitRatio); _perfCounters.Increment(PerfCounterName.HitRatioBase); } } else { if (updatePerfCounters && _perfCounters != null) { _perfCounters.Increment(PerfCounterName.Misses); _perfCounters.Increment(PerfCounterName.HitRatioBase); } } } private void WaitInsertBlock() { _insertBlock.WaitOne(INSERT_BLOCK_WAIT, false); } // public/internal members internal CacheUsage Usage { get { return _usage; } } internal MemoryCacheEntry AddOrGetExisting(MemoryCacheKey key, MemoryCacheEntry entry) { if (_useInsertBlock && entry.HasUsage()) { WaitInsertBlock(); } MemoryCacheEntry existingEntry = null; MemoryCacheEntry toBeReleasedEntry = null; bool added = false; lock (_entriesLock) { if (_disposed == 0) { existingEntry = _entries[key] as MemoryCacheEntry; // has it expired? if (existingEntry != null && existingEntry.UtcAbsExp <= DateTime.UtcNow) { toBeReleasedEntry = existingEntry; toBeReleasedEntry.State = EntryState.RemovingFromCache; existingEntry = null; } // can we add entry to the cache? if (existingEntry == null) { entry.State = EntryState.AddingToCache; added = true; _entries[key] = entry; } } } // release outside of lock RemoveFromCache(toBeReleasedEntry, CacheEntryRemovedReason.Expired, delayRelease: true); if (added) { // add outside of lock AddToCache(entry); } // update outside of lock UpdateExpAndUsage(existingEntry); // Call Release after the new entry has been completely added so // that the CacheItemRemovedCallback can take a dependency on the newly inserted item. if (toBeReleasedEntry != null) { toBeReleasedEntry.Release(_cache, CacheEntryRemovedReason.Expired); } return existingEntry; } internal void BlockInsert() { _insertBlock.Reset(); _useInsertBlock = true; } internal void CopyTo(IDictionary h) { lock (_entriesLock) { if (_disposed == 0) { foreach (DictionaryEntry e in _entries) { MemoryCacheKey key = e.Key as MemoryCacheKey; MemoryCacheEntry entry = e.Value as MemoryCacheEntry; if (entry.UtcAbsExp > DateTime.UtcNow) { h[key.Key] = entry.Value; } } } } } internal int Count { get { return _entries.Count; } } public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) { // disable CacheExpires timer _expires.EnableExpirationTimer(false); // build array list of entries ArrayList entries = new ArrayList(_entries.Count); lock (_entriesLock) { foreach (DictionaryEntry e in _entries) { MemoryCacheEntry entry = e.Value as MemoryCacheEntry; entries.Add(entry); } foreach (MemoryCacheEntry entry in entries) { MemoryCacheKey key = entry as MemoryCacheKey; entry.State = EntryState.RemovingFromCache; _entries.Remove(key); } } // release entries outside of lock foreach (MemoryCacheEntry entry in entries) { RemoveFromCache(entry, CacheEntryRemovedReason.CacheSpecificEviction); } // MemoryCacheStatistics has been disposed, and therefore nobody should be using // _insertBlock except for potential threads in WaitInsertBlock (which won't care if we call Close). Dbg.Assert(_useInsertBlock == false, "_useInsertBlock == false"); _insertBlock.Close(); // Don't need to call GC.SuppressFinalize(this) for sealed types without finalizers. } } internal MemoryCacheEntry Get(MemoryCacheKey key) { MemoryCacheEntry entry = _entries[key] as MemoryCacheEntry; // has it expired? if (entry != null && entry.UtcAbsExp <= DateTime.UtcNow) { Remove(key, entry, CacheEntryRemovedReason.Expired); entry = null; } // update outside of lock UpdateExpAndUsage(entry); return entry; } internal MemoryCacheEntry Remove(MemoryCacheKey key, MemoryCacheEntry entryToRemove, CacheEntryRemovedReason reason) { MemoryCacheEntry entry = null; lock (_entriesLock) { if (_disposed == 0) { // get current entry entry = _entries[key] as MemoryCacheEntry; // remove if it matches the entry to be removed (but always remove if entryToRemove is null) if (entryToRemove == null || object.ReferenceEquals(entry, entryToRemove)) { if (entry != null) { entry.State = EntryState.RemovingFromCache; _entries.Remove(key); } } else { entry = null; } } } // release outside of lock RemoveFromCache(entry, reason); return entry; } internal void Set(MemoryCacheKey key, MemoryCacheEntry entry) { if (_useInsertBlock && entry.HasUsage()) { WaitInsertBlock(); } MemoryCacheEntry existingEntry = null; bool added = false; lock (_entriesLock) { if (_disposed == 0) { existingEntry = _entries[key] as MemoryCacheEntry; if (existingEntry != null) { existingEntry.State = EntryState.RemovingFromCache; } entry.State = EntryState.AddingToCache; added = true; _entries[key] = entry; } } CacheEntryRemovedReason reason = CacheEntryRemovedReason.Removed; if (existingEntry != null) { if (existingEntry.UtcAbsExp <= DateTime.UtcNow) { reason = CacheEntryRemovedReason.Expired; } RemoveFromCache(existingEntry, reason, delayRelease: true); } if (added) { AddToCache(entry); } // Call Release after the new entry has been completely added so // that the CacheItemRemovedCallback can take a dependency on the newly inserted item. if (existingEntry != null) { existingEntry.Release(_cache, reason); } } internal long TrimInternal(int percent) { Dbg.Assert(percent <= 100, "percent <= 100"); int count = Count; int toTrim = 0; // do we need to drop a percentage of entries? if (percent > 0) { toTrim = (int)Math.Ceiling(((long)count * (long)percent) / 100D); // would this leave us above MAX_COUNT? int minTrim = count - MAX_COUNT; if (toTrim < minTrim) { toTrim = minTrim; } } // do we need to trim? if (toTrim <= 0 || _disposed == 1) { return 0; } int trimmed = 0; // total number of entries trimmed int trimmedOrExpired = 0; #if DEBUG int beginTotalCount = count; #endif trimmedOrExpired = _expires.FlushExpiredItems(true); if (trimmedOrExpired < toTrim) { trimmed = _usage.FlushUnderUsedItems(toTrim - trimmedOrExpired); trimmedOrExpired += trimmed; } if (trimmed > 0 && _perfCounters != null) { // Update values for perfcounters _perfCounters.IncrementBy(PerfCounterName.Trims, trimmed); } #if DEBUG Dbg.Trace("MemoryCacheStore", "TrimInternal:" + " beginTotalCount=" + beginTotalCount + ", endTotalCount=" + count + ", percent=" + percent + ", trimmed=" + trimmed); #endif return trimmedOrExpired; } internal void UnblockInsert() { _useInsertBlock = false; _insertBlock.Set(); } } }
/* * TreeDictionary.cs - Generic dictionary class, implemented as a tree. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace Generics { using System; public sealed class TreeDictionary<KeyT, ValueT> : TreeBase<KeyT, ValueT>, IDictionary<KeyT, ValueT>, ICloneable { // Constructor. public TreeDictionary() : base(null) {} public TreeDictionary(IComparer<KeyT> cmp) : base(cmp) {} // Implement the IDictionary<KeyT, ValueT> interface. public void Add(KeyT key, ValueT value) { AddItem(key, value, true); } public void Clear() { ClearAllItems(); } public bool Contains(KeyT key) { return ContainsItem(key); } public IDictionaryIterator<KeyT, ValueT> GetIterator() { return new TreeDictionaryIterator<KeyT, ValueT> (GetInOrderIterator()); } public void Remove(KeyT key) { RemoveItem(key); } public ValueT this[KeyT key] { get { return LookupItem(key); } set { AddItem(key, value, false); } } public ICollection<KeyT> Keys { get { return new TreeKeyCollection<KeyT, ValueT>(this); } } public ICollection<ValueT> Values { get { return new TreeValueCollection<KeyT, ValueT>(this); } } // Implement the ICollection<DictionaryEntry<KeyT, ValueT>> interface. public void CopyTo(DictionaryEntry<KeyT, ValueT>[] array, int index) { TreeBase.TreeIterator<KeyT, ValueT> iterator; iterator = GetInOrderIterator(); while(iterator.MoveNext()) { array[index++] = new DictionaryEntry<KeyT, ValueT> (iterator.Key, iterator.Value); } } public int Count { get { return count; } } public bool IsFixedSize { get { return false; } } public bool IsReadOnly { get { return false; } } public bool IsSynchronized { get { return false; } } public Object SyncRoot { get { return this; } } // Implement the IIterable<DictionaryEntry<KeyT, ValueT>> interface. IIterator< DictionaryEntry<KeyT, ValueT> > IIterable< DictionaryEntry<KeyT, ValueT> >.GetIterator() { return GetIterator(); } // Get the in-order dictionary iterator for the key and value collections. // Needed to get around the "protected" permissions in "TreeBase". private TreeBase.TreeBaseIterator<KeyT, ValueT> GetDictIterator() { return GetInOrderIterator(); } // Iterator class for tree dictionaries. private sealed class TreeDictionaryIterator<KeyT, ValueT> : IDictionaryIterator<KeyT, ValueT> { // Internal state. private TreeBase.TreeBaseIterator<KeyT, ValueT> iterator; // Constructor. public TreeDictionaryIterator (TreeBase.TreeBaseIterator<KeyT, ValueT> iterator) { this.iterator = iterator; } // Implement the IIterator<DictionaryEntry<KeyT, ValueT>> interface. public bool MoveNext() { return iterator.MoveNext(); } public void Reset() { iterator.Reset(); } public void Remove() { iterator.Remove(); } public DictionaryEntry<KeyT, ValueT> Current { get { return new DictionaryEntry<KeyT, ValueT> (iterator.Key, iterator.Value); } } // Implement the IDictionaryIterator<KeyT, ValueT> interface. public KeyT Key { get { return iterator.Key; } } public ValueT Value { get { return iterator.Value; } set { iterator.Value = value; } } }; // class TreeDictionaryIterator<KeyT, ValueT> // Key iterator class for tree dictionaries. private sealed class TreeKeyIterator<KeyT, ValueT> : IIterator<KeyT> { // Internal state. private TreeBase.TreeBaseIterator<KeyT, ValueT> iterator; // Constructor. public TreeKeyIterator (TreeBase.TreeBaseIterator<KeyT, ValueT> iterator) { this.iterator = iterator; } // Implement the IIterator<KeyT> interface. public bool MoveNext() { return iterator.MoveNext(); } public void Reset() { iterator.Reset(); } public void Remove() { iterator.Remove(); } public KeyT Current { get { return iterator.Key; } } }; // class TreeKeyIterator<KeyT, ValueT> // Value iterator class for tree dictionaries. private sealed class TreeValueIterator<KeyT, ValueT> : IIterator<ValueT> { // Internal state. private TreeBase.TreeBaseIterator<KeyT, ValueT> iterator; // Constructor. public TreeValueIterator (TreeBase.TreeBaseIterator<KeyT, ValueT> iterator) { this.iterator = iterator; } // Implement the IIterator<ValueT> interface. public bool MoveNext() { return iterator.MoveNext(); } public void Reset() { iterator.Reset(); } public void Remove() { iterator.Remove(); } public ValueT Current { get { return iterator.Value; } } }; // class TreeValueIterator<KeyT, ValueT> // Collection of keys in a tree dictionary. private sealed class TreeKeyCollection<KeyT, ValueT> : ICollection<KeyT> { // Internal state. private TreeDictionary<KeyT, ValueT> dict; // Constructor. public TreeKeyCollection(TreeDictionary<KeyT, ValueT> dict) { this.dict = dict; } // Implement the ICollection interface. public void CopyTo(KeyT[] array, int index) { IIterator<KeyT> iterator = GetIterator(); while(iterator.MoveNext()) { array[index++] = iterator.Current; } } public int Count { get { return dict.Count; } } public bool IsFixedSize { get { return dict.IsFixedSize; } } public bool IsReadOnly { get { return dict.IsReadOnly; } } public bool IsSynchronized { get { return dict.IsSynchronized; } } public Object SyncRoot { get { return dict.SyncRoot; } } // Implement the IIterable<KeyT> interface. public IIterator<KeyT> GetIterator() { return new TreeKeyIterator<KeyT, ValueT> (dict.GetDictIterator()); } }; // class TreeKeyCollection<KeyT, ValueT> // Collection of values in a tree dictionary. private sealed class TreeValueCollection<KeyT, ValueT> : ICollection<ValueT> { // Internal state. private TreeDictionary<KeyT, ValueT> dict; // Constructor. public TreeValueCollection(TreeDictionary<KeyT, ValueT> dict) { this.dict = dict; } // Implement the ICollection interface. public void CopyTo(ValueT[] array, int index) { IIterator<ValueT> iterator = GetIterator(); while(iterator.MoveNext()) { array[index++] = iterator.Current; } } public int Count { get { return dict.Count; } } public bool IsFixedSize { get { return dict.IsFixedSize; } } public bool IsReadOnly { get { return dict.IsReadOnly; } } public bool IsSynchronized { get { return dict.IsSynchronized; } } public Object SyncRoot { get { return dict.SyncRoot; } } // Implement the IIterable<ValueT> interface. public IIterator<ValueT> GetIterator() { return new TreeValueIterator<KeyT, ValueT> (dict.GetDictIterator()); } }; // class TreeValueCollection<KeyT, ValueT> }; // class TreeDictionary<T> }; // namespace Generics
// // 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; namespace Microsoft.Azure.Management.Sql { /// <summary> /// The Windows Azure SQL Database management API provides a RESTful set of /// web services that interact with Windows Azure SQL Database services to /// manage your databases. The API enables users to create, retrieve, /// update, and delete databases and servers. /// </summary> public static partial class ServerRecommendedActionOperationsExtensions { /// <summary> /// Returns details of a recommended action. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerRecommendedActionOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL Server advisor. /// </param> /// <param name='recommendedActionName'> /// Required. The name of the Azure SQL Server recommended action. /// </param> /// <returns> /// Represents the response to a get recommended action request. /// </returns> public static RecommendedActionGetResponse Get(this IServerRecommendedActionOperations operations, string resourceGroupName, string serverName, string advisorName, string recommendedActionName) { return Task.Factory.StartNew((object s) => { return ((IServerRecommendedActionOperations)s).GetAsync(resourceGroupName, serverName, advisorName, recommendedActionName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns details of a recommended action. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerRecommendedActionOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL Server advisor. /// </param> /// <param name='recommendedActionName'> /// Required. The name of the Azure SQL Server recommended action. /// </param> /// <returns> /// Represents the response to a get recommended action request. /// </returns> public static Task<RecommendedActionGetResponse> GetAsync(this IServerRecommendedActionOperations operations, string resourceGroupName, string serverName, string advisorName, string recommendedActionName) { return operations.GetAsync(resourceGroupName, serverName, advisorName, recommendedActionName, CancellationToken.None); } /// <summary> /// Returns list of recommended actions for this advisor. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerRecommendedActionOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL Server advisor. /// </param> /// <returns> /// Represents the response to a list recommended actions request. /// </returns> public static RecommendedActionListResponse List(this IServerRecommendedActionOperations operations, string resourceGroupName, string serverName, string advisorName) { return Task.Factory.StartNew((object s) => { return ((IServerRecommendedActionOperations)s).ListAsync(resourceGroupName, serverName, advisorName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns list of recommended actions for this advisor. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerRecommendedActionOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL Server advisor. /// </param> /// <returns> /// Represents the response to a list recommended actions request. /// </returns> public static Task<RecommendedActionListResponse> ListAsync(this IServerRecommendedActionOperations operations, string resourceGroupName, string serverName, string advisorName) { return operations.ListAsync(resourceGroupName, serverName, advisorName, CancellationToken.None); } /// <summary> /// Updates recommended action state. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerRecommendedActionOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL Server advisor. /// </param> /// <param name='recommendedActionName'> /// Required. The name of the Azure SQL Server recommended action. /// </param> /// <param name='parameters'> /// Required. The required parameters for updating recommended action /// state. /// </param> /// <returns> /// Represents the response to an update recommended action request. /// </returns> public static RecommendedActionUpdateResponse Update(this IServerRecommendedActionOperations operations, string resourceGroupName, string serverName, string advisorName, string recommendedActionName, RecommendedActionUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IServerRecommendedActionOperations)s).UpdateAsync(resourceGroupName, serverName, advisorName, recommendedActionName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates recommended action state. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerRecommendedActionOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL Server advisor. /// </param> /// <param name='recommendedActionName'> /// Required. The name of the Azure SQL Server recommended action. /// </param> /// <param name='parameters'> /// Required. The required parameters for updating recommended action /// state. /// </param> /// <returns> /// Represents the response to an update recommended action request. /// </returns> public static Task<RecommendedActionUpdateResponse> UpdateAsync(this IServerRecommendedActionOperations operations, string resourceGroupName, string serverName, string advisorName, string recommendedActionName, RecommendedActionUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, serverName, advisorName, recommendedActionName, parameters, CancellationToken.None); } } }
using System; using System.Collections; using System.Data; using PCSComUtils.Admin.DS; using PCSComUtils.Common; using PCSComUtils.Common.BO; using PCSComUtils.Framework.ReportFrame.DS; using PCSComUtils.PCSExc; namespace PCSComUtils.Framework.ReportFrame.BO { public class ReportManagementBO { private const string THIS = "PCSComUtils.Framework.ReportFrame.BO.ReportManagementBO"; /// <summary> /// Default constructor /// </summary> public ReportManagementBO() { } #region IObjectBO Members /// <Description> /// This method not implements yet /// </Description> /// <Inputs> /// Value object /// </Inputs> /// <Outputs> /// N/A /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// Created: 28-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pObjectDetail) { const string METHOD_NAME = THIS + ".Add()"; throw new PCSException(ErrorCode.NOT_IMPLEMENT, METHOD_NAME, new Exception()); } //************************************************************************** /// <Description> /// This method not implements yet /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// Created: 28-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(object pObjectVO) { sys_ReportVO voReport = (sys_ReportVO)pObjectVO; sys_ReportAndGroupDS dsReportAndGroup = new sys_ReportAndGroupDS(); // delete data in sys_ReportAndGroup dsReportAndGroup.DeleteByReportID(voReport.ReportID); // delete data in sys_ReportDrillDown where master id is selected report id sys_ReportDrillDownDS dsDrillDown = new sys_ReportDrillDownDS(); dsDrillDown.Delete(voReport.ReportID); // delete data in sys_ReportFields sys_ReportFieldsDS dsReportFields = new sys_ReportFieldsDS(); dsReportFields.Delete(voReport.ReportID); // delete data in sys_ReportPara sys_ReportParaDS dsReportPara = new sys_ReportParaDS(); dsReportPara.Delete(voReport.ReportID); // retrieve history of this report sys_ReportHistoryVO voReportHistory = new sys_ReportHistoryVO(); sys_ReportHistoryDS dsReportHistory = new sys_ReportHistoryDS(); sys_ReportHistoryParaDS dsHistoryPara = new sys_ReportHistoryParaDS(); ArrayList arrHistory = new ArrayList(); arrHistory = dsReportHistory.ListByReport(voReport.ReportID); // delete all data in sys_ReportHistoryPara related to each history if (arrHistory.Count > 0) { for (int i = 0; i < arrHistory.Count - 1; i++) { voReportHistory = (sys_ReportHistoryVO)arrHistory[i]; dsHistoryPara.Delete(voReportHistory.HistoryID); } } // delete data in sys_ReportHistory dsReportHistory.DeleteByReportID(voReport.ReportID); // delete data in sys_Report sys_ReportDS dsReport = new sys_ReportDS(); dsReport.Delete(voReport.ReportID); } //************************************************************************** /// <Description> /// This method not implements yet /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// Created: 28-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID, string VOclass) { const string METHOD_NAME = THIS + ".GetObjectVO()"; throw new PCSException(ErrorCode.NOT_IMPLEMENT, METHOD_NAME, new Exception()); } //************************************************************************** /// <Description> /// This method not implements yet /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// Created: 28-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet dstData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; throw new PCSException(ErrorCode.NOT_IMPLEMENT, METHOD_NAME, new Exception()); } //************************************************************************** /// <Description> /// This method not implements yet /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// Created: 28-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pObjectDetail) { const string METHOD_NAME = THIS + ".Update()"; throw new PCSException(ErrorCode.NOT_IMPLEMENT, METHOD_NAME, new Exception()); } //************************************************************************** /// <Description> /// This method uses to get all data /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// Created: 28-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { sys_ReportDS dsSysReport = new sys_ReportDS(); return dsSysReport.List(); } //************************************************************************** /// <Description> /// This method uses to get all report data of a group /// </Description> /// <Inputs> /// Group ID /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// Created: 29-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List(string pstrGroupID) { sys_ReportDS dsSysReport = new sys_ReportDS(); return dsSysReport.List(pstrGroupID); } //************************************************************************** /// <Description> /// This method uses to get all report data of a group by user role /// </Description> /// <Inputs> /// Group ID /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// Created: 29-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet ListByUser(string pstrGroupID, string pstrUserName) { // get user id int intUserID = new Sys_UserDS().GetUserIDByUserName(pstrUserName); sys_ReportDS dsSysReport = new sys_ReportDS(); return dsSysReport.ListByUser(pstrGroupID, intUserID); } //************************************************************************** /// <Description> /// This method uses to get all report data of a group by user role /// </Description> /// <Inputs> /// Group ID /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// Created: 29-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public ArrayList GetAllReports(string pstrGroupID, string pstrUserName) { // get user id int intUserID = new Sys_UserDS().GetUserIDByUserName(pstrUserName); sys_ReportDS dsSysReport = new sys_ReportDS(); return dsSysReport.GetAllReports(pstrGroupID, intUserID); } #endregion #region Public Methods //************************************************************************** /// <Description> /// This method uses to check whether a report has drill down report or not /// </Description> /// <Inputs> /// Report ID /// </Inputs> /// <Outputs> /// bool /// </Outputs> /// <Returns> /// true: if has drill down | false: if has no drill down /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 01-Feb-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public ArrayList GetDrillDownReports(string pstrReportID) { sys_ReportDrillDownDS dsReportDrillDown = new sys_ReportDrillDownDS(); return dsReportDrillDown.GetObjectVOs(pstrReportID); } //************************************************************************** /// <Description> /// This method uses to check whether a report has drill down report or not /// </Description> /// <Inputs> /// Master Report ID, Detail Report ID /// </Inputs> /// <Outputs> /// bool /// </Outputs> /// <Returns> /// true: if has drill down | false: if has no drill down /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 01-Feb-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public ArrayList GetDrillDownReports(string pstrMasterReportID, string pstrDetailReportID) { sys_ReportDrillDownDS dsReportDrillDown = new sys_ReportDrillDownDS(); return dsReportDrillDown.GetObjectVOs(pstrMasterReportID, pstrDetailReportID); } //************************************************************************** /// <Description> /// This method uses to change up order of a row in sys_ReportAndGroup /// </Description> /// <Inputs> /// Report ID /// </Inputs> /// <Outputs> /// changes /// </Outputs> /// <Returns> /// bool /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// Created: 30-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public bool MoveUpReport(string pstrReportID) { bool blnResult = false; sys_ReportAndGroupDS dsReportAndGroup = new sys_ReportAndGroupDS(); sys_ReportAndGroupVO voCurrentObject = new sys_ReportAndGroupVO(); sys_ReportAndGroupVO voPreviousObject = new sys_ReportAndGroupVO(); ArrayList arrReportAndGroup = new ArrayList(); string strGroupID = dsReportAndGroup.GetGroupIDByReportID(pstrReportID); // get all record from sys_ReportAndGroup arrReportAndGroup = dsReportAndGroup.GetObjectVOs(strGroupID); for (int i = 0; i < arrReportAndGroup.Count; i++) { sys_ReportAndGroupVO voReportAndGroup = (sys_ReportAndGroupVO)arrReportAndGroup[i]; if (voReportAndGroup.ReportID.Equals(pstrReportID)) { int intCurrentOrder = voReportAndGroup.ReportOrder; // if current order is the top then cannot move up any more if (intCurrentOrder <= 1) { // return false blnResult = false; } else { // get previous report voPreviousObject = (sys_ReportAndGroupVO)arrReportAndGroup[i-1]; // get current report voCurrentObject = (sys_ReportAndGroupVO)arrReportAndGroup[i]; // switch order voCurrentObject.ReportOrder = voPreviousObject.ReportOrder; voPreviousObject.ReportOrder = intCurrentOrder; // update two rows in database dsReportAndGroup.Update(voPreviousObject); dsReportAndGroup.Update(voCurrentObject); // return true blnResult = true; } } } return blnResult; } //************************************************************************** /// <Description> /// This method uses to change down of a row in sys_ReportAndGroup /// </Description> /// <Inputs> /// ReportID /// </Inputs> /// <Outputs> /// changes /// </Outputs> /// <Returns> /// bool /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 30-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public bool MoveDownReport(string pstrReportID) { bool blnResult = false; sys_ReportAndGroupDS dsReportAndGroup = new sys_ReportAndGroupDS(); sys_ReportAndGroupVO voNextObject = new sys_ReportAndGroupVO(); sys_ReportAndGroupVO voCurrentObject = new sys_ReportAndGroupVO(); ArrayList arrReportAndGroup = new ArrayList(); string strGroupID = dsReportAndGroup.GetGroupIDByReportID(pstrReportID); arrReportAndGroup = dsReportAndGroup.GetObjectVOs(strGroupID); for (int i = 0; i < arrReportAndGroup.Count; i++) { sys_ReportAndGroupVO voReportAndGroup = (sys_ReportAndGroupVO)arrReportAndGroup[i]; if (voReportAndGroup.ReportID.Equals(pstrReportID)) { int intCurrentOrder = voReportAndGroup.ReportOrder; // if current order reach the bottom then return false if (intCurrentOrder >= arrReportAndGroup.Count) { blnResult = false; } else { // destination report voNextObject = (sys_ReportAndGroupVO)arrReportAndGroup[i+1]; // current report voCurrentObject = (sys_ReportAndGroupVO)arrReportAndGroup[i]; // switch order voCurrentObject.ReportOrder = voNextObject.ReportOrder; voNextObject.ReportOrder = intCurrentOrder; //update two rows into database dsReportAndGroup.Update(voNextObject); dsReportAndGroup.Update(voCurrentObject); blnResult = true; } } } return blnResult; } //************************************************************************** /// <Description> /// This method uses to make a copy of specified report to another group, /// also copy all data relative to report (sys_ReportAndGroup, sys_ReportDrillDown, /// sys_ReportFields, sys_ReportPara). /// </Description> /// <Inputs> /// Source ReportID, Destination GroupID /// </Inputs> /// <Outputs> /// New report id /// </Outputs> /// <Returns> /// new report id /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 03-Jan-2005 /// 11-Jan-2005 /// </History> /// <Notes> /// Return newly report id /// </Notes> //************************************************************************** public object CopyReport(string pstrReportID, string pstrGroupID, out int ointReportOrder) { const string METHOD_NAME = THIS + ".CopyReport()"; const int REPORT_ID_MAX_LENGTH = 20; const string CODE_DATE_FORMAT = "yyyyMMddHHmmssfff"; UtilsBO boUtils = new UtilsBO(); sys_ReportDS dsReport = new sys_ReportDS(); sys_ReportVO voReport; // use to add new report to selected group sys_ReportAndGroupVO voReportAndGroup = new sys_ReportAndGroupVO(); sys_ReportAndGroupDS dsReportAndGroup = new sys_ReportAndGroupDS(); // use to copy report para sys_ReportParaDS dsReportPara = new sys_ReportParaDS(); // use to copy report fields sys_ReportFieldsDS dsReportFields = new sys_ReportFieldsDS(); // use to copy drill down report sys_ReportDrillDownDS dsReportDrillDown = new sys_ReportDrillDownDS(); // get the data of selected object voReport = (sys_ReportVO) (dsReport.GetObjectVO(pstrReportID)); #region Copy report // make a copy report sys_ReportVO voCopiedReport = new sys_ReportVO(); voCopiedReport = voReport; // get database server date time DateTime dtmDB = boUtils.GetDBDate(); // report ID = yyyyMMddHHmmssfff voCopiedReport.ReportID = dtmDB.ToString(CODE_DATE_FORMAT); if (voCopiedReport.ReportID.Length > REPORT_ID_MAX_LENGTH) throw new PCSBOException(ErrorCode.MESSAGE_VALUE_TOO_LONG, METHOD_NAME, new Exception()); voCopiedReport.ReportName = Constants.COPY_OF + voCopiedReport.ReportName; // save new report to database dsReport.Add(voCopiedReport); #endregion #region Add new report to group voReportAndGroup.GroupID = pstrGroupID; voReportAndGroup.ReportID = voCopiedReport.ReportID; // increase report order by one in group. voReportAndGroup.ReportOrder = dsReportAndGroup.GetMaxReportOrder(pstrGroupID) + 1; // save data dsReportAndGroup.Add(voReportAndGroup); ointReportOrder = voReportAndGroup.ReportOrder; #endregion #region Copy all data relative from old report to new report #region ReportPara // get all parameter(s) sys_ReportParaVO voReportPara; ArrayList arrParas = dsReportPara.GetObjectVOs(pstrReportID); // make a copy of each parameter if (arrParas.Count > 0) { for (int i = 0; i < arrParas.Count; i++) { voReportPara = (sys_ReportParaVO)(arrParas[i]); // assign new report id voReportPara.ReportID = voCopiedReport.ReportID; // save new para dsReportPara.Add(voReportPara); } } #endregion #region ReportFields // get all report fields sys_ReportFieldsVO voReportFields; ArrayList arrFields = dsReportFields.GetObjectVOs(pstrReportID); // make a copy of each field if (arrFields.Count > 0) { for (int i = 0; i < arrFields.Count; i++) { voReportFields = (sys_ReportFieldsVO)arrFields[i]; // assign new report id voReportFields.ReportID = voCopiedReport.ReportID; // save new field dsReportFields.Add(voReportFields); } } #endregion #region ReportDrillDown // get all drill down report sys_ReportDrillDownVO voReportDrillDown; ArrayList arrDrillDown = dsReportDrillDown.GetObjectVOs(pstrReportID); // make a copy each drill down report if (arrDrillDown.Count > 0) { for (int i = 0; i < arrDrillDown.Count; i++) { voReportDrillDown = (sys_ReportDrillDownVO)arrDrillDown[i]; // assign new report id voReportDrillDown.MasterReportID = voCopiedReport.ReportID; // save new drill down dsReportDrillDown.Add(voReportDrillDown); } } #endregion #endregion return voCopiedReport; } //************************************************************************** /// <Description> /// This method uses to get max report order of specified group). /// </Description> /// <Inputs> /// GroupID /// </Inputs> /// <Outputs> /// Max order /// </Outputs> /// <Returns> /// int /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 03-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public int GetMaxReportOrder(string pstrGroupID) { sys_ReportAndGroupDS dsReportAndGroup = new sys_ReportAndGroupDS(); return dsReportAndGroup.GetMaxReportOrder(pstrGroupID); } //************************************************************************** /// <Description> /// This method uses to get all report /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// ArrayList /// </Outputs> /// <Returns> /// ArrayList /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public ArrayList GetAllReports() { sys_ReportDS dsSysReport = new sys_ReportDS(); return dsSysReport.GetAllReports(); } /// <summary> /// Get all report in a group /// </summary> /// <param name="pstrGroupID">Group ID</param> /// <returns>List of Report in a group</returns> public ArrayList GetAllReports(string pstrGroupID) { sys_ReportDS dsSysReport = new sys_ReportDS(); return dsSysReport.GetAllReports(pstrGroupID); } //************************************************************************** /// <Description> /// This method uses to get the ReportName of ReportID in sys_Report /// </Description> /// <Inputs> /// ReportID /// </Inputs> /// <Outputs> /// ReportName /// </Outputs> /// <Returns> /// string /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 20-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public string GetReportName(string pstrReportID) { sys_ReportDS dsReport = new sys_ReportDS(); return dsReport.GetReportName(pstrReportID); } //************************************************************************** /// <Description> /// This method uses to get all role of user /// </Description> /// <Inputs> /// user id /// </Inputs> /// <Outputs> /// array list /// </Outputs> /// <Returns> /// ArrayList /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Apr-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public ArrayList GetRoles(string pstrUserName) { int intUserID = new Sys_UserDS().GetUserIDByUserName(pstrUserName); Sys_UserToRoleDS dsUserRole = new Sys_UserToRoleDS(); return dsUserRole.ListRoleByUser(intUserID); } //************************************************************************** /// <Description> /// This method uses to check if user has right to view this report or not /// </Description> /// <Inputs> /// ReportID /// </Inputs> /// <Outputs> /// bool /// </Outputs> /// <Returns> /// true if ok, false if not /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 06-Apr-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public bool HasRight(string pstrReportID, string pstrUserName) { Sys_Report_RoleDS dsReportRole = new Sys_Report_RoleDS(); return dsReportRole.HasRight(pstrReportID, GetRoles(pstrUserName)); } #endregion /// <summary> /// Get sys_ReportAndGroupVO object /// </summary> /// <param name="pstrReportID">ReportID</param> /// <param name="pstrGroupID">GroupID</param> /// <returns>sys_ReportAndGroupVO</returns> public object GetReportAndGroupObject(string pstrReportID, string pstrGroupID) { sys_ReportAndGroupDS dsRnG = new sys_ReportAndGroupDS(); return dsRnG.GetObjectVO(pstrReportID, pstrGroupID); } /// <summary> /// Swap report order /// </summary> /// <param name="pobjSourceReport">Source Report</param> /// <param name="pobjDestReport">Destination Report</param> public void SwapReport(object pobjSourceReport, object pobjDestReport) { sys_ReportAndGroupDS dsReportAndGroup = new sys_ReportAndGroupDS(); dsReportAndGroup.Update(pobjSourceReport); dsReportAndGroup.Update(pobjDestReport); } /// <summary> /// Swap group order /// </summary> /// <param name="pobjSourceGroup">Source Group</param> /// <param name="pobjDestGroup">Destination Group</param> public void SwapGroup(object pobjSourceGroup, object pobjDestGroup) { sys_ReportGroupDS dsReportGroup = new sys_ReportGroupDS(); // update object dsReportGroup.Update(pobjSourceGroup); dsReportGroup.Update(pobjDestGroup); } } }
// v-minch using System; using System.Collections.Generic; using System.Text; using System.Globalization; /// <summary> /// UInt32.Parse(System.string) /// </summary> public class UInt32Parse1 { public static int Main() { UInt32Parse1 ui32parse1 = new UInt32Parse1(); TestLibrary.TestFramework.BeginTestCase("UInt32Parse1"); if (ui32parse1.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { 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; retVal = PosTest7() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; return retVal; } #region PostiveTest public bool PosTest1() { bool retVal = true; UInt32 uintA; TestLibrary.TestFramework.BeginScenario("PosTest1: the string corresponding UInt32 is UInt32 MinValue "); try { string strA = UInt32.MinValue.ToString(); uintA = UInt32.Parse(strA); if (uintA != 0) { TestLibrary.TestFramework.LogError("001", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; UInt32 uintA; TestLibrary.TestFramework.BeginScenario("PosTest2: the string corresponding UInt32 is UInt32 MaxValue "); try { string strA = UInt32.MaxValue.ToString(); uintA = UInt32.Parse(strA); if (uintA != UInt32.MaxValue) { TestLibrary.TestFramework.LogError("003", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; UInt32 uintA; TestLibrary.TestFramework.BeginScenario("PosTest3: the string corresponding UInt32 is normal UInt32 "); try { UInt32 uintTest = (UInt32)this.GetInt32(0,Int32.MaxValue); string strA = uintTest.ToString(); uintA = UInt32.Parse(strA); if (uintA != uintTest) { TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; UInt32 uintA; TestLibrary.TestFramework.BeginScenario("PosTest4: the string format is [ws][sign]digits[ws] 1"); try { UInt32 uintTest = (UInt32)this.GetInt32(0, Int32.MaxValue); string strA = "+" + uintTest.ToString(); uintA = UInt32.Parse(strA); if (uintA != uintTest) { TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; UInt32 uintA; TestLibrary.TestFramework.BeginScenario("PosTest5: the string format is [ws][sign]digits[ws] 2"); try { UInt32 uintTest = (UInt32)this.GetInt32(0, Int32.MaxValue); string strA = "\u0009" + "+" + uintTest.ToString(); uintA = UInt32.Parse(strA); if (uintA != uintTest) { TestLibrary.TestFramework.LogError("009", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; UInt32 uintA; TestLibrary.TestFramework.BeginScenario("PosTest6: the string format is [ws][sign]digits[ws] 3"); try { UInt32 uintTest = (UInt32)this.GetInt32(0, Int32.MaxValue); string strA = uintTest.ToString() + "\u0020"; uintA = UInt32.Parse(strA); if (uintA != uintTest) { TestLibrary.TestFramework.LogError("011", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; UInt32 uintA; TestLibrary.TestFramework.BeginScenario("PosTest7: the string format is [ws][sign]digits[ws] 4"); try { UInt32 uintTest = (UInt32)this.GetInt32(0, Int32.MaxValue); string strA = "\u0009" + "+" + uintTest.ToString() + "\u0020"; uintA = UInt32.Parse(strA); if (uintA != uintTest) { TestLibrary.TestFramework.LogError("013", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; UInt32 uintA; TestLibrary.TestFramework.BeginScenario("NegTest1: the parameter string is null"); try { string strA = null; uintA = UInt32.Parse(strA); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N001", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; UInt32 uintA; TestLibrary.TestFramework.BeginScenario("NegTest2: the parameter string is not of the correct format 1"); try { string strA = "abcd"; uintA = UInt32.Parse(strA); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; UInt32 uintA; TestLibrary.TestFramework.BeginScenario("NegTest3: the parameter string is not of the correct format 2"); try { string strA = "b12345d"; uintA = UInt32.Parse(strA); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N003", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; UInt32 uintA; TestLibrary.TestFramework.BeginScenario("NegTest4: the parameter string corresponding number is less than UInt32 minValue"); try { Int32 Testint = (-1) * this.GetInt32(1, Int32.MaxValue); string strA = Testint.ToString(); uintA = UInt32.Parse(strA); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; UInt32 uintA; TestLibrary.TestFramework.BeginScenario("NegTest5: the parameter string corresponding number is larger than UInt32 maxValue"); try { UInt32 uinta = UInt32.MaxValue; UInt32 uintb = (UInt32)this.GetInt32(1, Int32.MaxValue); UInt64 TestUint = (UInt64)uinta + (UInt64)uintb; string strA = TestUint.ToString(); uintA = UInt32.Parse(strA); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N005", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region ForTestObject private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
#region Copyright /*Copyright (C) 2015 Wosad 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. */ #endregion 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 Wosad.WebApi.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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using Xunit.Abstractions; using System.IO; using System.Xml.Schema; using System.Xml.XPath; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_Misc", Desc = "")] public class TC_SchemaSet_Misc : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_Misc(ITestOutputHelper output) { _output = output; } public bool bWarningCallback; public bool bErrorCallback; public int errorCount; public int warningCount; public bool WarningInnerExceptionSet = false; public bool ErrorInnerExceptionSet = false; private void Initialize() { bWarningCallback = bErrorCallback = false; errorCount = warningCount = 0; WarningInnerExceptionSet = ErrorInnerExceptionSet = false; } //hook up validaton callback private void ValidationCallback(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) { _output.WriteLine("WARNING: "); bWarningCallback = true; warningCount++; WarningInnerExceptionSet = (args.Exception.InnerException != null); _output.WriteLine("\nInnerExceptionSet : " + WarningInnerExceptionSet + "\n"); } else if (args.Severity == XmlSeverityType.Error) { _output.WriteLine("ERROR: "); bErrorCallback = true; errorCount++; ErrorInnerExceptionSet = (args.Exception.InnerException != null); _output.WriteLine("\nInnerExceptionSet : " + ErrorInnerExceptionSet + "\n"); } _output.WriteLine(args.Message); // Print the error to the screen. } //----------------------------------------------------------------------------------- //[Variation(Desc = "v1 - Bug110823 - SchemaSet.Add is holding onto some of the schema files after adding", Priority = 1)] [InlineData()] [Theory] public void v1() { XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); using (XmlTextReader xtr = new XmlTextReader(Path.Combine(TestData._Root, "bug110823.xsd"))) { xss.Add(XmlSchema.Read(xtr, null)); } } //[Variation(Desc = "v2 - Bug115049 - XSD: content model validation for an invalid root element should be abandoned", Priority = 2)] [InlineData()] [Theory] public void v2() { Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(null, Path.Combine(TestData._Root, "bug115049.xsd")); ss.Compile(); //create reader XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); settings.Schemas.Add(ss); XmlReader vr = XmlReader.Create(Path.Combine(TestData._Root, "bug115049.xml"), settings); while (vr.Read()) ; CError.Compare(errorCount, 1, "Error Count mismatch!"); return; } //[Variation(Desc = "v4 - 243300 - We are not correctly handling xs:anyType as xsi:type in the instance", Priority = 2)] [InlineData()] [Theory] public void v4() { string xml = @"<a xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xsi:type='xsd:anyType'>1242<b/></a>"; Initialize(); XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = new XmlUrlResolver(); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlReader vr = XmlReader.Create(new StringReader(xml), settings, (string)null); while (vr.Read()) ; CError.Compare(errorCount, 0, "Error Count mismatch!"); CError.Compare(warningCount, 1, "Warning Count mismatch!"); return; } /* Parameters = file name , is custom xml namespace System.Xml.Tests */ //[Variation(Desc = "v20 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v10.xsd", 2, false })] [InlineData("bug264908_v10.xsd", 2, false)] //[Variation(Desc = "v19 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v9.xsd", 5, true })] [InlineData("bug264908_v9.xsd", 5, true)] //[Variation(Desc = "v18 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v8.xsd", 5, false })] [InlineData("bug264908_v8.xsd", 5, false)] //[Variation(Desc = "v17 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v7.xsd", 4, false })] [InlineData("bug264908_v7.xsd", 4, false)] //[Variation(Desc = "v16 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v6.xsd", 4, true })] [InlineData("bug264908_v6.xsd", 4, true)] //[Variation(Desc = "v15 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v5.xsd", 4, false })] [InlineData("bug264908_v5.xsd", 4, false)] //[Variation(Desc = "v14 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v4.xsd", 4, true })] [InlineData("bug264908_v4.xsd", 4, true)] //[Variation(Desc = "v13 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v3.xsd", 1, true })] [InlineData("bug264908_v3.xsd", 1, true)] //[Variation(Desc = "v12 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v2.xsd", 1, true })] [InlineData("bug264908_v2.xsd", 1, true)] //[Variation(Desc = "v11 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v1.xsd", 3, true })] [InlineData("bug264908_v1.xsd", 3, true)] [Theory] public void v10(object param0, object param1, object param2) { string xmlFile = param0.ToString(); int count = (int)param1; bool custom = (bool)param2; string attName = "blah"; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(null, Path.Combine(TestData._Root, xmlFile)); ss.Compile(); //test the count CError.Compare(ss.Count, count, "Count of SchemaSet not matched!"); //make sure the correct schema is in the set if (custom) { foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == attName) return; } Assert.True(false); } return; } //[Variation(Desc = "v21 - Bug 319346 - Chameleon add of a schema into the xml namespace", Priority = 1)] [InlineData()] [Theory] public void v20() { string xmlns = @"http://www.w3.org/XML/1998/namespace"; string attName = "blah"; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(xmlns, Path.Combine(TestData._Root, "bug264908_v11.xsd")); ss.Compile(); //test the count CError.Compare(ss.Count, 3, "Count of SchemaSet not matched!"); //make sure the correct schema is in the set foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == attName) return; } Assert.True(false); } //[Variation(Desc = "v22 - Bug 338038 - Component should be additive into the Xml namespace", Priority = 1)] [InlineData()] [Theory] public void v21() { string xmlns = @"http://www.w3.org/XML/1998/namespace"; string attName = "blah1"; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(xmlns, Path.Combine(TestData._Root, "bug338038_v1.xsd")); ss.Compile(); //test the count CError.Compare(ss.Count, 4, "Count of SchemaSet not matched!"); //make sure the correct schema is in the set foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == attName) return; } Assert.True(false); } //[Variation(Desc = "v23 - Bug 338038 - Conflicting components in custome xml namespace System.Xml.Tests be caught", Priority = 1)] [InlineData()] [Theory] public void v22() { string xmlns = @"http://www.w3.org/XML/1998/namespace"; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(xmlns, Path.Combine(TestData._Root, "bug338038_v2.xsd")); try { ss.Compile(); } catch (XmlSchemaException e) { _output.WriteLine(e.Message); CError.Compare(ss.Count, 4, "Count of SchemaSet not matched!"); return; } Assert.True(false); } //[Variation(Desc = "v24 - Bug 338038 - Change type of xml:lang to decimal in custome xml namespace System.Xml.Tests", Priority = 1)] [InlineData()] [Theory] public void v24() { string attName = "lang"; string newtype = "decimal"; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3a.xsd")); ss.Compile(); CError.Compare(ss.Count, 4, "Count of SchemaSet not matched!"); foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == attName) { CError.Compare(a.AttributeSchemaType.QualifiedName.Name, newtype, "Incorrect type for xml:lang"); return; } } Assert.True(false); } //[Variation(Desc = "v25 - Bug 338038 - Conflicting definitions for xml attributes in two schemas", Priority = 1)] [InlineData()] [Theory] public void v25() { XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3a.xsd")); ss.Compile(); try { ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3b.xsd")); ss.Compile(); } catch (XmlSchemaException e) { _output.WriteLine(e.Message); CError.Compare(ss.Count, 6, "Count of SchemaSet not matched!"); return; } Assert.True(false); } //[Variation(Desc = "v26 - Bug 338038 - Change type of xml:lang to decimal and xml:base to short in two steps", Priority = 1)] [InlineData()] [Theory] public void v26() { XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4a.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4b.xsd")); ss.Compile(); foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == "lang") { CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "decimal", "Incorrect type for xml:lang"); } if (a.QualifiedName.Name == "base") { CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "short", "Incorrect type for xml:base"); } } CError.Compare(ss.Count, 6, "Count of SchemaSet not matched!"); return; } //[Variation(Desc = "v27 - Bug 338038 - Add new attributes to the already present xml namespace System.Xml.Tests", Priority = 1)] [InlineData()] [Theory] public void v27() { XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4a.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v5b.xsd")); ss.Compile(); foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == "blah") { CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "int", "Incorrect type for xml:lang"); } } CError.Compare(ss.Count, 6, "Count of SchemaSet not matched!"); return; } //[Variation(Desc = "v28 - Bug 338038 - Add new attributes to the already present xml namespace System.Xml.Tests, remove default ns schema", Priority = 1)] [InlineData()] [Theory] public void v28() { string xmlns = @"http://www.w3.org/XML/1998/namespace"; XmlSchema schema = null; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd")); ss.Compile(); foreach (XmlSchema s in ss.Schemas(xmlns)) { schema = s; } ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4a.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v5b.xsd")); ss.Compile(); ss.Remove(schema); ss.Compile(); foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == "blah") { CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "int", "Incorrect type for xml:lang"); } } CError.Compare(ss.Count, 5, "Count of SchemaSet not matched!"); return; } //Regressions - Bug Fixes private void Callback1(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) { _output.WriteLine("WARNING Recieved"); bWarningCallback = true; warningCount++; CError.Compare(args.Exception.InnerException == null, false, "Inner Exception not set"); } } //[Variation(Desc = "v100 - Bug 320502 - XmlSchemaSet: while throwing a warning for invalid externals we do not set the inner exception", Priority = 1)] [InlineData()] [Theory] public void v100() { string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:include schemaLocation='bogus'/></xs:schema>"; Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(Callback1); ss.Add(null, new XmlTextReader(new StringReader(xsd))); ss.Compile(); CError.Compare(warningCount, 1, "Warning Count mismatch!"); return; } //[Variation(Desc = "v101 - Bug 339706 - XmlSchemaSet: Compile on the set fails when a compiled schema containing notation is already present", Priority = 1)] [InlineData()] [Theory] public void v101() { string xsd1 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:notation name='a' public='a'/></xs:schema>"; string xsd2 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:element name='root'/></xs:schema>"; Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(Callback1); ss.Add(null, new XmlTextReader(new StringReader(xsd1))); ss.Compile(); ss.Add(null, new XmlTextReader(new StringReader(xsd2))); ss.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v102 - Bug 337850 - XmlSchemaSet: Type already declared error when redefined schema is added to the set before the redefining schema.", Priority = 1)] [InlineData()] [Theory] public void v102() { Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(null, Path.Combine(TestData._Root, "schZ013c.xsd")); ss.Add(null, Path.Combine(TestData._Root, "schZ013a.xsd")); ss.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v104 - CodeCoverage- XmlSchemaSet: add precompiled subs groups, global elements, attributes and types to another compiled SOM.", Priority = 1, Params = new object[] { false })] [InlineData(false)] //[Variation(Desc = "v103 - CodeCoverage- XmlSchemaSet: add precompiled subs groups, global elements, attributes and types to another compiled set.", Priority = 1, Params = new object[] { true })] [InlineData(true)] [Theory] public void v103(object param0) { bool addset = (bool)param0; Initialize(); XmlSchemaSet ss1 = new XmlSchemaSet(); ss1.XmlResolver = new XmlUrlResolver(); ss1.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss1.Add(null, Path.Combine(TestData._Root, "Misc103_x.xsd")); ss1.Compile(); CError.Compare(ss1.Count, 1, "Schema Set 1 Count mismatch!"); XmlSchemaSet ss2 = new XmlSchemaSet(); ss2.XmlResolver = new XmlUrlResolver(); ss2.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema s = ss2.Add(null, Path.Combine(TestData._Root, "Misc103_a.xsd")); ss2.Compile(); CError.Compare(ss1.Count, 1, "Schema Set 1 Count mismatch!"); if (addset) { ss1.Add(ss2); CError.Compare(ss1.GlobalElements.Count, 7, "Schema Set 1 GlobalElements Count mismatch!"); CError.Compare(ss1.GlobalAttributes.Count, 2, "Schema Set 1 GlobalAttributes Count mismatch!"); CError.Compare(ss1.GlobalTypes.Count, 6, "Schema Set 1 GlobalTypes Count mismatch!"); } else { ss1.Add(s); CError.Compare(ss1.GlobalElements.Count, 2, "Schema Set 1 GlobalElements Count mismatch!"); CError.Compare(ss1.GlobalAttributes.Count, 0, "Schema Set 1 GlobalAttributes Count mismatch!"); CError.Compare(ss1.GlobalTypes.Count, 2, "Schema Set 1 GlobalTypes Count mismatch!"); } /***********************************************/ XmlSchemaSet ss3 = new XmlSchemaSet(); ss3.XmlResolver = new XmlUrlResolver(); ss3.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss3.Add(null, Path.Combine(TestData._Root, "Misc103_c.xsd")); ss3.Compile(); ss1.Add(ss3); CError.Compare(ss1.GlobalElements.Count, 8, "Schema Set 1 GlobalElements Count mismatch!"); return; } //[Variation(Desc = "v103 - Reference to a component from no namespace System.Xml.Tests an explicit import of no namespace System.Xml.Tests throw a validation warning", Priority = 1)] [InlineData()] [Theory] public void v105() { Initialize(); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.XmlResolver = new XmlUrlResolver(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); schemaSet.Add(null, Path.Combine(TestData._Root, "Misc105.xsd")); CError.Compare(warningCount, 1, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v106 - Adding a compiled SoS(schema for schema) to a set causes type collision error", Priority = 1)] [InlineData()] [Theory] public void v106() { Initialize(); XmlSchemaSet ss1 = new XmlSchemaSet(); ss1.XmlResolver = new XmlUrlResolver(); ss1.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlReaderSettings settings = new XmlReaderSettings(); #pragma warning disable 0618 settings.ProhibitDtd = false; #pragma warning restore 0618 XmlReader r = XmlReader.Create(Path.Combine(TestData._Root, "XMLSchema.xsd"), settings); ss1.Add(null, r); ss1.Compile(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); foreach (XmlSchema s in ss1.Schemas()) { ss.Add(s); } ss.Add(null, Path.Combine(TestData._Root, "xsdauthor.xsd")); ss.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v107 - XsdValidatingReader: InnerException not set on validation warning of a schemaLocation not loaded.", Priority = 1)] [InlineData()] [Theory] public void v107() { string strXml = @"<root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='a bug356711_a.xsd' xmlns:a='a'></root>"; Initialize(); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.XmlResolver = new XmlUrlResolver(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); schemaSet.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd")); XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = new XmlUrlResolver(); settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation; settings.Schemas.Add(schemaSet); settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); settings.ValidationType = ValidationType.Schema; XmlReader vr = XmlReader.Create(new StringReader(strXml), settings); while (vr.Read()) ; CError.Compare(warningCount, 1, "Warning Count mismatch!"); CError.Compare(WarningInnerExceptionSet, true, "Inner Exception not set!"); return; } //[Variation(Desc = "v108 - XmlSchemaSet.Add() should not trust compiled state of the schema being added", Priority = 1)] [InlineData()] [Theory] public void v108() { string strSchema1 = @" <xs:schema targetNamespace='http://bar' xmlns='http://bar' xmlns:x='http://foo' elementFormDefault='qualified' attributeFormDefault='unqualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:import namespace='http://foo'/> <xs:element name='bar'> <xs:complexType> <xs:sequence> <xs:element ref='x:foo'/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> "; string strSchema2 = @"<xs:schema targetNamespace='http://foo' xmlns='http://foo' xmlns:x='http://bar' elementFormDefault='qualified' attributeFormDefault='unqualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:import namespace='http://bar'/> <xs:element name='foo'> <xs:complexType> <xs:sequence> <xs:element ref='x:bar'/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; Initialize(); XmlSchemaSet set = new XmlSchemaSet(); set.XmlResolver = new XmlUrlResolver(); ValidationEventHandler handler = new ValidationEventHandler(ValidationCallback); set.ValidationEventHandler += handler; XmlSchema s1 = null; using (XmlReader r = XmlReader.Create(new StringReader(strSchema1))) { s1 = XmlSchema.Read(r, handler); set.Add(s1); } set.Compile(); // Now load set 2 set = new XmlSchemaSet(); set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema s2 = null; using (XmlReader r = XmlReader.Create(new StringReader(strSchema2))) { s2 = XmlSchema.Read(r, handler); } XmlSchemaImport import = (XmlSchemaImport)s2.Includes[0]; import.Schema = s1; import = (XmlSchemaImport)s1.Includes[0]; import.Schema = s2; set.Add(s1); set.Reprocess(s1); set.Add(s2); set.Reprocess(s2); set.Compile(); s2 = null; using (XmlReader r = XmlReader.Create(new StringReader(strSchema2))) { s2 = XmlSchema.Read(r, handler); } set = new XmlSchemaSet(); set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); import = (XmlSchemaImport)s2.Includes[0]; import.Schema = s1; import = (XmlSchemaImport)s1.Includes[0]; import.Schema = s2; set.Add(s1); set.Reprocess(s1); set.Add(s2); set.Reprocess(s2); set.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 1, "Error Count mismatch"); return; } //[Variation(Desc = "v109 - 386243, Adding a chameleon schema against to no namespace throws unexpected warnings", Priority = 1)] [InlineData()] [Theory] public void v109() { Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add("http://EmployeeTest.org", Path.Combine(TestData._Root, "EmployeeTypes.xsd")); ss.Add(null, Path.Combine(TestData._Root, "EmployeeTypes.xsd")); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v110 - 386246, ArgumentException 'item arleady added' error on a chameleon add done twice", Priority = 1)] [InlineData()] [Theory] public void v110() { Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema s1 = ss.Add("http://EmployeeTest.org", Path.Combine(TestData._Root, "EmployeeTypes.xsd")); XmlSchema s2 = ss.Add("http://EmployeeTest.org", Path.Combine(TestData._Root, "EmployeeTypes.xsd")); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v111 - 380805, Chameleon include compiled in one set added to another", Priority = 1)] [InlineData()] [Theory] public void v111() { Initialize(); XmlSchemaSet newSet = new XmlSchemaSet(); newSet.XmlResolver = new XmlUrlResolver(); newSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema chameleon = newSet.Add(null, Path.Combine(TestData._Root, "EmployeeTypes.xsd")); newSet.Compile(); CError.Compare(newSet.GlobalTypes.Count, 10, "GlobalTypes count mismatch!"); XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); sc.Add(chameleon); sc.Add(null, Path.Combine(TestData._Root, "baseEmployee.xsd")); sc.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v112 - 382035, schema set tables not cleared as expected on reprocess", Priority = 1)] [InlineData()] [Theory] public void v112() { Initialize(); XmlSchemaSet set2 = new XmlSchemaSet(); set2.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema includedSchema = set2.Add(null, Path.Combine(TestData._Root, "bug382035a1.xsd")); set2.Compile(); XmlSchemaSet set = new XmlSchemaSet(); set.XmlResolver = new XmlUrlResolver(); set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema mainSchema = set.Add(null, Path.Combine(TestData._Root, "bug382035a.xsd")); set.Compile(); XmlReader r = XmlReader.Create(Path.Combine(TestData._Root, "bug382035a1.xsd")); XmlSchema reParsedInclude = XmlSchema.Read(r, new ValidationEventHandler(ValidationCallback)); ((XmlSchemaExternal)mainSchema.Includes[0]).Schema = reParsedInclude; set.Reprocess(mainSchema); set.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v113 - Set InnerException on XmlSchemaValidationException while parsing typed values", Priority = 1)] [InlineData()] [Theory] public void v113() { string strXml = @"<root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xs='http://www.w3.org/2001/XMLSchema' xsi:type='xs:int'>a</root>"; Initialize(); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); settings.ValidationType = ValidationType.Schema; XmlReader vr = XmlReader.Create(new StringReader(strXml), settings); while (vr.Read()) ; CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 1, "Error Count mismatch!"); CError.Compare(ErrorInnerExceptionSet, true, "Inner Exception not set!"); return; } //[Variation(Desc = "v114 - XmlSchemaSet: InnerException not set on parse errors during schema compilation", Priority = 1)] [InlineData()] [Theory] public void v114() { string strXsd = @"<xs:schema elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='date' type='date'/> <xs:simpleType name='date'> <xs:restriction base='xs:int'> <xs:enumeration value='a'/> </xs:restriction> </xs:simpleType> </xs:schema>"; Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(XmlSchema.Read(new StringReader(strXsd), new ValidationEventHandler(ValidationCallback))); ss.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 1, "Error Count mismatch!"); CError.Compare(ErrorInnerExceptionSet, true, "Inner Exception not set!"); return; } //[Variation(Desc = "v116 - 405327 NullReferenceExceptions while accessing obsolete properties in the SOM", Priority = 1)] [InlineData()] [Theory] public void v116() { #pragma warning disable 0618 XmlSchemaAttribute attribute = new XmlSchemaAttribute(); object attributeType = attribute.AttributeType; XmlSchemaElement element = new XmlSchemaElement(); object elementType = element.ElementType; XmlSchemaType schemaType = new XmlSchemaType(); object BaseSchemaType = schemaType.BaseSchemaType; #pragma warning restore 0618 } //[Variation(Desc = "v117 - 398474 InnerException not set on XmlSchemaException, when xs:pattern has an invalid regular expression", Priority = 1)] [InlineData()] [Theory] public void v117() { string strXsdv117 = @"<?xml version='1.0' encoding='utf-8' ?> <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='doc'> <xs:complexType> <xs:sequence> <xs:element name='value' maxOccurs='unbounded'> <xs:simpleType> <xs:restriction base='xs:string'> <xs:pattern value='(?r:foo)'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; Initialize(); using (StringReader reader = new StringReader(strXsdv117)) { XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(XmlSchema.Read(reader, ValidationCallback)); ss.Compile(); CError.Compare(ErrorInnerExceptionSet, true, "\nInner Exception not set\n"); } return; } //[Variation(Desc = "v118 - 424904 Not getting unhandled attributes on particle", Priority = 1)] [InlineData()] [Theory] public void v118() { using (XmlReader r = new XmlTextReader(Path.Combine(TestData._Root, "Bug424904.xsd"))) { XmlSchema s = XmlSchema.Read(r, null); XmlSchemaSet set = new XmlSchemaSet(); set.XmlResolver = new XmlUrlResolver(); set.Add(s); set.Compile(); XmlQualifiedName name = new XmlQualifiedName("test2", "http://foo"); XmlSchemaComplexType test2type = s.SchemaTypes[name] as XmlSchemaComplexType; XmlSchemaParticle p = test2type.ContentTypeParticle; XmlAttribute[] att = p.UnhandledAttributes; Assert.False(att == null || att.Length < 1); } } //[Variation(Desc = "v120 - 397633 line number and position not set on the validation error for an invalid xsi:type value", Priority = 1)] [InlineData()] [Theory] public void v120() { using (XmlReader schemaReader = XmlReader.Create(Path.Combine(TestData._Root, "Bug397633.xsd"))) { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); sc.Add("", schemaReader); sc.Compile(); XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; readerSettings.Schemas = sc; using (XmlReader docValidatingReader = XmlReader.Create(Path.Combine(TestData._Root, "Bug397633.xml"), readerSettings)) { XmlDocument doc = new XmlDocument(); try { doc.Load(docValidatingReader); doc.Validate(null); } catch (XmlSchemaValidationException ex) { if (ex.LineNumber == 1 && ex.LinePosition == 2 && !string.IsNullOrEmpty(ex.SourceUri)) { return; } } } } Assert.True(false); } //[Variation(Desc = "v120a.XmlDocument.Load non-validating reader.Expect IOE.")] [InlineData()] [Theory] public void v120a() { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; using (XmlReader reader = XmlReader.Create(Path.Combine(TestData._Root, "Bug397633.xml"), readerSettings)) { XmlDocument doc = new XmlDocument(); try { doc.Load(reader); doc.Validate(null); } catch (XmlSchemaValidationException ex) { _output.WriteLine(ex.Message); return; } } Assert.True(false); } //[Variation(Desc = "444196: XmlReader.MoveToNextAttribute returns incorrect results")] [InlineData()] [Theory] public void v124() { Initialize(); string XamlPresentationNamespace = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"; string XamlToParse = "<pfx0:DrawingBrush TileMode=\"Tile\" Viewbox=\"foobar\" />"; string xml = " <xs:schema " + " xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"" + " targetNamespace=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" " + " elementFormDefault=\"qualified\" " + " attributeFormDefault=\"unqualified\"" + " >" + "" + " <xs:element name=\"DrawingBrush\" type=\"DrawingBrushType\" />" + "" + " <xs:complexType name=\"DrawingBrushType\">" + " <xs:attribute name=\"Viewbox\" type=\"xs:string\" />" + " <xs:attribute name=\"TileMode\" type=\"xs:string\" />" + " </xs:complexType>" + " </xs:schema>"; XmlSchema schema = XmlSchema.Read(new StringReader(xml), null); schema.TargetNamespace = XamlPresentationNamespace; XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.XmlResolver = new XmlUrlResolver(); schemaSet.Add(schema); schemaSet.Compile(); XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ConformanceLevel = ConformanceLevel.Fragment; readerSettings.ValidationType = ValidationType.Schema; readerSettings.Schemas = schemaSet; NameTable nameTable = new NameTable(); XmlNamespaceManager namespaces = new XmlNamespaceManager(nameTable); namespaces.AddNamespace("pfx0", XamlPresentationNamespace); namespaces.AddNamespace(string.Empty, XamlPresentationNamespace); XmlParserContext parserContext = new XmlParserContext(nameTable, namespaces, null, null, null, null, null, null, XmlSpace.None); using (XmlReader xmlReader = XmlReader.Create(new StringReader(XamlToParse), readerSettings, parserContext)) { xmlReader.Read(); xmlReader.MoveToAttribute(0); xmlReader.MoveToNextAttribute(); xmlReader.MoveToNextAttribute(); xmlReader.MoveToNextAttribute(); xmlReader.MoveToAttribute(0); if (xmlReader.MoveToNextAttribute()) return; } Assert.True(false); } //[Variation(Desc = "615444 XmlSchema.Write ((XmlWriter)null) throws InvalidOperationException instead of ArgumentNullException")] [Fact] public void v125() { XmlSchema xs = new XmlSchema(); try { xs.Write((XmlWriter)null); } catch (InvalidOperationException) { return; } Assert.True(false); } //[Variation(Desc = "Dev10_40561 Redefine Chameleon: Unexpected qualified name on local particle")] [InlineData()] [Theory] public void Dev10_40561() { Initialize(); string xml = @"<?xml version='1.0' encoding='utf-8'?><e1 xmlns='ns-a'> <c23 xmlns='ns-b'/></e1>"; XmlSchemaSet set = new XmlSchemaSet(); set.XmlResolver = new XmlUrlResolver(); string path = Path.Combine(TestData.StandardPath, "xsd10", "SCHEMA", "schN11_a.xsd"); set.Add(null, path); set.Compile(); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = set; using (XmlReader reader = XmlReader.Create(new StringReader(xml), settings)) { try { while (reader.Read()) ; _output.WriteLine("XmlSchemaValidationException was not thrown"); Assert.True(false); } catch (XmlSchemaValidationException e) { _output.WriteLine(e.Message); } } CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } // Test failure on ILC: Test depends on Xml Serialization and requires reflection on a LOT of types under System.Xml.Schema namespace. // Rd.xml with "<Namespace Name="System.Xml.Schema" Dynamic="Required Public" />" lets this test pass but we should probably be // fixing up XmlSerializer's own rd.xml rather than the test here. [Fact] public void GetBuiltinSimpleTypeWorksAsEcpected() { Initialize(); string xml = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + Environment.NewLine + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + Environment.NewLine + " <xs:simpleType>" + Environment.NewLine + " <xs:restriction base=\"xs:anySimpleType\" />" + Environment.NewLine + " </xs:simpleType>" + Environment.NewLine + "</xs:schema>"; XmlSchema schema = new XmlSchema(); XmlSchemaSimpleType stringType = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String); schema.Items.Add(stringType); StringWriter sw = new StringWriter(); schema.Write(sw); CError.Compare(sw.ToString(), xml, "Mismatch"); return; } //[Variation(Desc = "Dev10_40509 Assert and NRE when validate the XML against the XSD")] [InlineData()] [Theory] public void Dev10_40509() { Initialize(); string xml = Path.Combine(TestData._Root, "bug511217.xml"); string xsd = Path.Combine(TestData._Root, "bug511217.xsd"); XmlSchemaSet s = new XmlSchemaSet(); s.XmlResolver = new XmlUrlResolver(); XmlReader r = XmlReader.Create(xsd); s.Add(null, r); s.Compile(); XmlReaderSettings rs = new XmlReaderSettings(); rs.ValidationType = ValidationType.Schema; using (XmlReader docValidatingReader = XmlReader.Create(xml, rs)) { XmlDocument doc = new XmlDocument(); doc.Load(docValidatingReader); doc.Schemas = s; doc.Validate(null); } CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "Dev10_40511 XmlSchemaSet::Compile throws XmlSchemaException for valid schema")] [InlineData()] [Theory] public void Dev10_40511() { Initialize(); string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:simpleType name='textType'> <xs:restriction base='xs:string'> <xs:minLength value='1' /> </xs:restriction> </xs:simpleType> <xs:simpleType name='statusCodeType'> <xs:restriction base='textType'> <xs:length value='6' /> </xs:restriction> </xs:simpleType> </xs:schema>"; XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); sc.Add("xs", XmlReader.Create(new StringReader(xsd))); sc.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "Dev10_40495 Undefined ComplexType error when loading schemas from in memory strings")] [InlineData()] [Theory] public void Dev10_40495() { Initialize(); const string schema1Str = @"<xs:schema xmlns:tns=""http://BizTalk_Server_Project2.Schema1"" xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" targetNamespace=""http://BizTalk_Server_Project2.Schema1"" xmlns:xs=""http://www.w3.org/2001/XMLSchema""> <xs:include schemaLocation=""S3"" /> <xs:include schemaLocation=""S2"" /> <xs:element name=""Root""> <xs:complexType> <xs:sequence> <xs:element name=""FxTypeElement""> <xs:complexType> <xs:complexContent mixed=""false""> <xs:extension base=""tns:FxType""> <xs:attribute name=""Field"" type=""xs:string"" /> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; const string schema2Str = @"<xs:schema xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema""> <xs:complexType name=""FxType""> <xs:attribute name=""Fx2"" type=""xs:string"" /> </xs:complexType> </xs:schema>"; const string schema3Str = @"<xs:schema xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema""> <xs:complexType name=""TestType""> <xs:attribute name=""Fx2"" type=""xs:string"" /> </xs:complexType> </xs:schema>"; XmlSchema schema1 = XmlSchema.Read(new StringReader(schema1Str), null); XmlSchema schema2 = XmlSchema.Read(new StringReader(schema2Str), null); XmlSchema schema3 = XmlSchema.Read(new StringReader(schema3Str), null); //schema1 has some xs:includes in it. Since all schemas are string based, XmlSchema on its own cannot load automatically //load these included schemas. We will resolve these schema locations schema1 and make them point to the correct //in memory XmlSchema objects ((XmlSchemaExternal)schema1.Includes[0]).Schema = schema3; ((XmlSchemaExternal)schema1.Includes[1]).Schema = schema2; XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.XmlResolver = new XmlUrlResolver(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); if (schemaSet.Add(schema1) != null) { //This compile will complain about Undefined complex Type tns:FxType and schemaSet_ValidationEventHandler will be //called with this error. schemaSet.Compile(); schemaSet.Reprocess(schema1); } CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "Dev10_64765 XmlSchemaValidationException.SourceObject is always null when using XPathNavigator.CheckValidity method")] [InlineData()] [Theory] public void Dev10_64765() { Initialize(); string xsd = "<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" + "<xsd:element name='some'>" + "</xsd:element>" + "</xsd:schema>"; string xml = "<root/>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); ValidateXPathNavigator(xml, CompileSchemaSet(xsd)); return; } private void ValidateXPathNavigator(string xml, XmlSchemaSet schemaSet) { XPathDocument doc = new XPathDocument(new StringReader(xml)); XPathNavigator nav = doc.CreateNavigator(); ValidateXPathNavigator(nav, schemaSet); } private void ValidateXPathNavigator(XPathNavigator nav, XmlSchemaSet schemaSet) { _output.WriteLine(nav.CheckValidity(schemaSet, OnValidationEvent) ? "Validation succeeded." : "Validation failed."); } private XmlSchemaSet CompileSchemaSet(string xsd) { XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.XmlResolver = new XmlUrlResolver(); schemaSet.Add(XmlSchema.Read(new StringReader(xsd), OnValidationEvent)); schemaSet.ValidationEventHandler += OnValidationEvent; schemaSet.Compile(); return schemaSet; } private void OnValidationEvent(object sender, ValidationEventArgs e) { XmlSchemaValidationException exception = e.Exception as XmlSchemaValidationException; if (exception == null || exception.SourceObject == null) { CError.Compare(exception != null, "exception == null"); CError.Compare(exception.SourceObject != null, "SourceObject == null"); return; } CError.Compare(exception.SourceObject.GetType().ToString(), "MS.Internal.Xml.Cache.XPathDocumentNavigator", "SourceObject.GetType"); _output.WriteLine("Exc: " + exception); } //[Variation(Desc = "Dev10_40563 XmlSchemaSet: Assert Failure with Chk Build.")] [InlineData()] [Theory] public void Dev10_40563() { Initialize(); string xsd = "<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" + "<xsd:element name='some'>" + "</xsd:element>" + "</xsd:schema>"; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add("http://www.w3.org/2001/XMLSchema", XmlReader.Create(new StringReader(xsd))); XmlReaderSettings rs = new XmlReaderSettings(); rs.ValidationType = ValidationType.Schema; rs.Schemas = ss; string input = "<root xml:space='default'/>"; using (XmlReader r1 = XmlReader.Create(new StringReader(input), rs)) { using (XmlReader r2 = XmlReader.Create(new StringReader(input), rs)) { while (r1.Read()) ; while (r2.Read()) ; } } CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "TFS_470020 Schema with substitution groups does not throw when content model is ambiguous")] [InlineData()] [Theory] public void TFS_470020() { Initialize(); string xml = @"<?xml version='1.0' encoding='utf-8' ?> <e3> <e2>1</e2> <e2>1</e2> </e3>"; string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' elementFormDefault='qualified'> <xs:element name='e1' type='xs:int'/> <xs:element name='e2' type='xs:int' substitutionGroup='e1'/> <xs:complexType name='t3'> <xs:sequence> <xs:element ref='e1' minOccurs='0' maxOccurs='1'/> <xs:element name='e2' type='xs:int' minOccurs='0' maxOccurs='1'/> </xs:sequence> </xs:complexType> <xs:element name='e3' type='t3'/> </xs:schema>"; XmlSchemaSet set = new XmlSchemaSet(); set.XmlResolver = new XmlUrlResolver(); set.Add(null, XmlReader.Create(new StringReader(xsd))); XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); doc.Schemas = set; doc.Validate(ValidationCallback); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 1, "Error Count mismatch!"); return; } } }
using System; using Xunit; using Scripting.SSharp.Runtime; using Scripting.SSharp; namespace UnitTests { /// <summary> /// Summary description for BaseAlgorithms /// </summary> public class BaseAlgorithms : IDisposable { public BaseAlgorithms() { RuntimeHost.Initialize(); EventBroker.ClearAllSubscriptions(); } public void Dispose() { RuntimeHost.CleanUp(); EventBroker.ClearAllSubscriptions(); } [Fact] public void IndexerDefinedByExplicitInterface() { Script script = Script.Compile(@" s = new SQLiteDataReader(); return s['Test Value'];"); RuntimeHost.AddType("SQLiteDataReader", typeof(SQLiteDataReader)); Assert.Equal(10, script.Execute()); } [Fact] public void BubbleSort() { object resultVal = Script.RunCode( @" a=[17,-2, 0,-3, 5, 3,1, 2, 55]; for (i=0; i < a.Length; i=i+1) for (j=i+1; j < a.Length; j=j+1) if (a[i] > a[j] ) { temp = a[i]; a[i] = a[j]; a[j] = temp; } s = 'Results:'; for (i=0; i < a.Length; i++) if (i!=0) s = s + ',' + a[i]; else s += a[i];" ); Assert.Equal("Results:-3,-2,0,1,2,3,5,17,55", resultVal); } [Fact] public void QuickSort() { object result = Script.RunCode(@" function swap(array, a, b) { tmp=array[a]; array[a]=array[b]; array[b]=tmp; } function partition(array, begin, end, pivot) { piv=array[pivot]; swap(array, pivot, end-1); store=begin; for(ix=begin; ix < end-1; ix++) { if(array[ix]<=piv) { swap(array, store, ix); store++; } } swap(array, end-1, store); return store; } function qsort(array, begin, end) { if(end-1>begin) { pivot=begin+(end-begin) / 2; pivot=partition(array, begin, end, pivot); qsort(array, begin, pivot); qsort(array, pivot+1, end); } } a = [1,2,10,0,12,34,-9,5,3,3,4,1,23,4]; qsort(a, 0, a.Length); s=''; for (i=0; i < a.Length; i++) s = s+' '+a[i]; " ); Assert.Equal(" -9 0 1 1 2 3 3 4 4 5 10 12 23 34", result); } [Fact] public void SimplePrecondition() { object resultVal = Script.RunCode( @"function d(a,b,c) [ pre(a>0); post(); invariant(); ] { return 1; } d(1,2,3);" ); Assert.Equal((int)1, resultVal); } [Fact] public void SimplePreconditionWithException() { Assert.Throws<ScriptVerificationException>( () => Script.RunCode( @"function d(a,b,c) [ pre(a>0); post(); invariant(); ] { return 1; } d(-1,2,3);" )); } [Fact] public void UsingStatement() { object resultVal = Script.RunCode(@"using (Math) { return Pow(2,10); }"); Assert.Equal((double)1024, resultVal); } [Fact] public void GenericsArray() { object resultVal = Script.RunCode(@"v = new int[10]; for(i=0; i<v.Length; i++) v[i] = i; s = ''; foreach(i in v) s = s + i + ' '; a = new List<|string|>[10]; a[0] = new List<|string|>(); a[0].Add('Hello'); b = a[0].ToArray(); c = b[0];"); Assert.Equal("Hello", resultVal); } [Fact] public void OpertatorPresidence() { object resultVal = Script.RunCode(@"a=3; a-1>2;"); Assert.False((bool)resultVal); resultVal = Script.RunCode(@"a=3; a==1 | true;"); Assert.True((bool)resultVal); } [Fact] public void SimpleNameSpaces() { object resultVal = Script.RunCode(@"a = System.DateTime.Now;"); Assert.IsType<DateTime>(resultVal); } [Fact] public void NameSpaces() { object rez = Script.RunCode(@"a = System.Text.RegularExpressions.Regex.CacheSize;"); Assert.Equal(System.Text.RegularExpressions.Regex.CacheSize, rez); Assert.Equal(Scripting.SSharp.Runtime.RuntimeHost.Activator, Script.RunCode("return Scripting.SSharp.Runtime.RuntimeHost.Activator;")); } [Fact] public void ForBreak() { object resultVal = Script.RunCode(@" s = ''; for (i=0;i<3;i++) { for (j=0;j<5;j++) { if (j==3) break; s+='j'; } s+='i'; } "); Assert.Equal("jjjijjjijjji", resultVal); } [Fact] public void WhileBreak() { object resultVal = Script.RunCode(@" s = ''; for (i=0;i<3;i++) { j = 0; while(j<5) { if (j==3) break; s+='j'; j++; } s+='i'; } "); Assert.Equal("jjjijjjijjji", resultVal); } [Fact] public void ForEachBreak() { object resultVal = Script.RunCode(@" a=[1,2,4,3,4,5]; s = ''; for (i=0;i<3;i++) { foreach(j in a) { if (j==3) break; s+=j.ToString(); } s+='i'; } "); Assert.Equal("124i124i124i", resultVal); } [Fact] public void ProgReturn() { object resultVal = Script.RunCode(@" s = ''; for (i=0;i<3;i++) { for (j=0;j<5;j++) { if (j==2) break; s+='j'; } s+='i'; } return s; a = [17,-2, 0,-3, 5, 3,1, 2, 55]; for (i=0; i < a.Length; i=i+1) for (j=i+1; j < a.Length; j=j+1) if (a[i] > a[j] ) { temp = a[i]; a[i] = a[j]; a[j] = temp; } s = 'Results:'; for (i=0; i < a.Length; i++) if (i!=0) s = s + ',' + a[i]; else s += a[i];"); Assert.Equal("jjijjijji", resultVal); } [Fact] public void ForContinue() { object resultVal = Script.RunCode(@" s = ''; for (i=0;i<3;i++) { for (j=0;j<5;j++) { if (j==2) continue; s+=j.ToString(); } s+='i'; } return s;"); Assert.Equal("0134i0134i0134i", resultVal); } [Fact] public void FuncReturn() { object resultVal = Script.RunCode(@" s = ''; function Test(){ for (i=0;i<3;i++) { s+='i'; for (j=0;j<5;j++) { if (j==2) return s; s+=j.ToString(); } } } return Test();"); Assert.Equal("i01", resultVal); } [Fact] public void TryCatch() { Script result = Script.Compile(@" try { a = c/0; } catch(e) { msg = e.Message; } finally { return 'Message:'+msg; }"); result.Context.SetItem("c", 10); object resultVal = result.Execute(); Assert.IsType<string>(resultVal); } [Fact] public void ThrowException() { Assert.Throws<ArgumentNullException>( () => Script.RunCode(@" throw new ArgumentNullException('me'); ")); } [Fact] public void ExplicitTypeConvert() { object resultVal = Script.RunCode(@" a = 1.0; return (string)a; "); Assert.IsType<string>(resultVal); } [Fact] public void ComparingWithNull() { object resultVal = Script.RunCode(@" a = null; if (a!=null) { throw new Exception('This should not happen'); } else return 'OK'; "); Assert.Equal("OK", resultVal); } [Fact] public void ScriptCompilerCompilesWrongProgramm() { Assert.Throws<ArgumentException>( () => Script.RunCode(@" astNode = Compiler.Parse('wrong programm'); if (astNode != null) astNode.Execute(new ScriptContext()).Value; else throw new ArgumentException('Syntax Error'); ")); } [Fact] public void SwitchStatement() { object resultVal = Script.RunCode(@" a = 5; switch(a) { default: return 2; } "); Assert.Equal(2, resultVal); resultVal = Script.RunCode(@" a = 5; switch(a) { case 1: b = 3; case 5: b = 'Hello'; default: b = 2; } "); Assert.Equal("Hello", resultVal); resultVal = Script.RunCode(@" a = 5; switch(a) { case 5: b = 'Hello'; } "); Assert.Equal("Hello", resultVal); } [Fact] public void BaseOperatorsUnary() { ScriptContext context = new ScriptContext(); Script.RunCode(@" a = 4; b = 2; a++; b--; ", context); Assert.Equal(5, context.GetItem("a", true)); Assert.Equal(1, context.GetItem("b", true)); } [Fact] public void BaseOperatorIs() { ScriptContext context = new ScriptContext(); Script.RunCode(@" a = 4; result = a is int; ", context); Assert.True((bool)context.GetItem("result", true)); } [Fact] public void EventInvokation() { Script script2 = Script.Compile(@"function f(sender){ sender.test = 1;} c = new EventHelperInvocation(); c.test = 0; c.eva+=f; c.OnEva(); c.eva-=f; return c; "); EventHelperInvocation rez = (EventHelperInvocation)script2.Execute(); EventBroker.ClearAllSubscriptions(); Assert.Equal(1, rez.test); Assert.True(rez.IsEventNull()); Assert.False(EventBroker.HasSubscriptions); } [Fact] public void DuplicateEventSubscriptionSupported() { Script script2 = Script.Compile(@"function f(sender){ sender.test = 1;} c = new EventHelperInvocation(); c.test = 0; c.eva+=f; c.eva+=f; "); script2.Execute(); } [Fact] public void ContractScopeThrowsException() { Assert.Throws<ScriptVerificationException>( () => Script.RunCode(@" function F1(x) [ pre(x is int); post(x is int); invariant(x is int); ] { x = 10; x = 'heelo!'; } F1(2); ")); } [Fact] public void ContractScope() { object rez = Script.RunCode(@" function F1(x) [ pre(x is int); post(x is int); invariant(x is int); ] { x = 10; } F1(2); "); Assert.Equal(10, rez); } [Fact] public void PlusEqualOperator() { Script rez = Script.Compile(@" a = new SumOp(); a.a += 2; return a.a; "); RuntimeHost.AddType("SumOp", typeof(SumOp)); Assert.Equal(2, rez.Execute()); } [Fact] public void MissingNamespaceException() { Assert.Throws<ScriptIdNotFoundException>( () => Script.RunCode(@" MyMissingSpace.NullValue; ")); } [Fact] public void PostprocessingsSetsDeclaredFunctions() { object rez = Script.RunCode(@" return f(); function f() {return 1;} "); Assert.Equal(1, rez); } private class SumOp { public int a = 0; } [Fact] public void ScriptCreatesChar() { object rez = Script.RunCode(@" return (Char)char(';'); "); Assert.Equal(';', rez); } [Fact] public void BinaryOperatorHelpers() { object rez = Script.RunCode(@" a = null; return false && a.b; "); Assert.False((bool)rez); rez = Script.RunCode(@" a = null; return true || a.b; "); Assert.True((bool)rez); rez = Script.RunCode(@" return true && false; "); Assert.False((bool)rez); } [Fact] public void BitOperators() { object rez = Script.RunCode(@" a = 1; b = 2; return a|b; "); Assert.Equal(3, rez); rez = Script.RunCode(@" a = 1; b = 2; return a&b; "); Assert.Equal(0, rez); } [Fact] public void ComparingCharProperties() { object rez = Script.RunCode(@" c = new CharValueObject(); return c.CharValue == char('C'); "); Assert.True((bool)rez); } [Fact] public void DecimalValueTests() { object rez = Script.RunCode(@" d = new DecimalValueObject(); return d.V1 == d.V2; "); Assert.False((bool)rez); rez = Script.RunCode(@" d = new DecimalValueObject(); return d.V1 == d.V1; "); Assert.True((bool)rez); rez = Script.RunCode(@" d = new DecimalValueObject(); return d.V1 + d.V2; "); Assert.Equal(45m+5m, rez); rez = Script.RunCode(@" d = new DecimalValueObject(); return d.V1 > d.V2; "); Assert.True((bool)rez); rez = Script.RunCode(@" d = new DecimalValueObject(); return d.V1 < d.V2; "); Assert.False((bool)rez); rez = Script.RunCode(@" d = new DecimalValueObject(); return d.V1 == 45m; "); Assert.True((bool)rez); rez = Script.RunCode(@" d = new DecimalValueObject(); return d.V1 == 45; "); Assert.True((bool)rez); } [Fact] public void DecimalDivTests() { System.Int16 i16 = 10; System.Int32 i32 = 10; System.Int64 i64 = 10; System.Double d = 10; System.Single f = 10; System.Decimal dc = 2; object rez = null; IScriptContext context = new ScriptContext(); context.SetItem("i16", i16); context.SetItem("i32", i32); context.SetItem("i64", i64); context.SetItem("d", d); context.SetItem("f", f); context.SetItem("dc", dc); rez = Script.RunCode(@" return i16 / dc; ", context); Assert.Equal(i16/dc, rez); rez = Script.RunCode(@" return i32 / dc; ", context); Assert.Equal(i32 / dc, rez); rez = Script.RunCode(@" return i64 / dc; ", context); Assert.Equal(i64 / dc, rez); rez = Script.RunCode(@" return new decimal(f) / dc; ", context); Assert.Equal(new decimal(f) / dc, rez); rez = Script.RunCode(@" return new decimal(d) / dc; ", context); Assert.Equal(new decimal(d) / dc, rez); // Reverse rez = Script.RunCode(@" return dc / i16; ", context); Assert.Equal(dc / i16, rez); rez = Script.RunCode(@" return dc / i32; ", context); Assert.Equal(dc / i32, rez); rez = Script.RunCode(@" return dc / i64; ", context); Assert.Equal(dc / i64, rez); rez = Script.RunCode(@" return dc / new decimal(f); ", context); Assert.Equal(dc / new decimal(f), rez); rez = Script.RunCode(@" return dc / new decimal(d); ", context); Assert.Equal(dc / new decimal(d), rez); } [Fact] public void DecimalPlusTests() { System.Int16 i16 = 10; System.Int32 i32 = 10; System.Int64 i64 = 10; System.Double d = 10; System.Single f = 10; System.Decimal dc = 2; object rez = null; IScriptContext context = new ScriptContext(); context.SetItem("i16", i16); context.SetItem("i32", i32); context.SetItem("i64", i64); context.SetItem("d", d); context.SetItem("f", f); context.SetItem("dc", dc); rez = Script.RunCode(@" return i16 + dc; ", context); Assert.Equal(i16 + dc, rez); rez = Script.RunCode(@" return i32 + dc; ", context); Assert.Equal(i32 + dc, rez); rez = Script.RunCode(@" return i64 + dc; ", context); Assert.Equal(i64 + dc, rez); rez = Script.RunCode(@" return new decimal(f) + dc; ", context); Assert.Equal(new decimal(f) + dc, rez); rez = Script.RunCode(@" return new decimal(d) + dc; ", context); Assert.Equal(new decimal(d) + dc, rez); // Reverse rez = Script.RunCode(@" return dc + i16; ", context); Assert.Equal(dc + i16, rez); rez = Script.RunCode(@" return dc + i32; ", context); Assert.Equal(dc + i32, rez); rez = Script.RunCode(@" return dc + i64; ", context); Assert.Equal(dc + i64, rez); rez = Script.RunCode(@" return dc + new decimal(f); ", context); Assert.Equal(dc + new decimal(f), rez); rez = Script.RunCode(@" return dc + new decimal(d); ", context); Assert.Equal(dc + new decimal(d), rez); } [Fact] public void DecimalMinusTests() { System.Int16 i16 = 10; System.Int32 i32 = 10; System.Int64 i64 = 10; System.Double d = 10; System.Single f = 10; System.Decimal dc = 2; object rez = null; IScriptContext context = new ScriptContext(); context.SetItem("i16", i16); context.SetItem("i32", i32); context.SetItem("i64", i64); context.SetItem("d", d); context.SetItem("f", f); context.SetItem("dc", dc); rez = Script.RunCode(@" return i16 - dc; ", context); Assert.Equal(i16 - dc, rez); rez = Script.RunCode(@" return i32 - dc; ", context); Assert.Equal(i32 - dc, rez); rez = Script.RunCode(@" return i64 - dc; ", context); Assert.Equal(i64 - dc, rez); rez = Script.RunCode(@" return new decimal(f) - dc; ", context); Assert.Equal(new decimal(f) - dc, rez); rez = Script.RunCode(@" return new decimal(d) - dc; ", context); Assert.Equal(new decimal(d) - dc, rez); // Reverse rez = Script.RunCode(@" return dc - i16; ", context); Assert.Equal(dc - i16, rez); rez = Script.RunCode(@" return dc - i32; ", context); Assert.Equal(dc - i32, rez); rez = Script.RunCode(@" return dc - i64; ", context); Assert.Equal(dc - i64, rez); rez = Script.RunCode(@" return dc - new decimal(f); ", context); Assert.Equal(dc - new decimal(f), rez); rez = Script.RunCode(@" return dc - new decimal(d); ", context); Assert.Equal(dc - new decimal(d), rez); } [Fact] public void DecimalMulTests() { System.Int16 i16 = 10; System.Int32 i32 = 10; System.Int64 i64 = 10; System.Double d = 10; System.Single f = 10; System.Decimal dc = 2; object rez = null; IScriptContext context = new ScriptContext(); context.SetItem("i16", i16); context.SetItem("i32", i32); context.SetItem("i64", i64); context.SetItem("d", d); context.SetItem("f", f); context.SetItem("dc", dc); rez = Script.RunCode(@" return i16 * dc; ", context); Assert.Equal(i16 * dc, rez); rez = Script.RunCode(@" return i32 * dc; ", context); Assert.Equal(i32 * dc, rez); rez = Script.RunCode(@" return i64 * dc; ", context); Assert.Equal(i64 * dc, rez); rez = Script.RunCode(@" return new decimal(f) * dc; ", context); Assert.Equal(new decimal(f) * dc, rez); rez = Script.RunCode(@" return new decimal(d) * dc; ", context); Assert.Equal(new decimal(d) * dc, rez); // Reverse rez = Script.RunCode(@" return dc * i16; ", context); Assert.Equal(dc * i16, rez); rez = Script.RunCode(@" return dc * i32; ", context); Assert.Equal(dc * i32, rez); rez = Script.RunCode(@" return dc * i64; ", context); Assert.Equal(dc * i64, rez); rez = Script.RunCode(@" return dc * new decimal(f); ", context); Assert.Equal(dc * new decimal(f), rez); rez = Script.RunCode(@" return dc * new decimal(d); ", context); Assert.Equal(dc * new decimal(d), rez); } [Fact] public void DecimalModTests() { System.Int16 i16 = 10; System.Int32 i32 = 10; System.Int64 i64 = 10; System.Double d = 10; System.Single f = 10; System.Decimal dc = 2; object rez = null; IScriptContext context = new ScriptContext(); context.SetItem("i16", i16); context.SetItem("i32", i32); context.SetItem("i64", i64); context.SetItem("d", d); context.SetItem("f", f); context.SetItem("dc", dc); rez = Script.RunCode(@" return i16 % dc; ", context); Assert.Equal(i16 % dc, rez); rez = Script.RunCode(@" return i32 % dc; ", context); Assert.Equal(i32 % dc, rez); rez = Script.RunCode(@" return i64 % dc; ", context); Assert.Equal(i64 % dc, rez); rez = Script.RunCode(@" return new decimal(f) % dc; ", context); Assert.Equal(new decimal(f) % dc, rez); rez = Script.RunCode(@" return new decimal(d) % dc; ", context); Assert.Equal(new decimal(d) % dc, rez); // Reverse rez = Script.RunCode(@" return dc % i16; ", context); Assert.Equal(dc % i16, rez); rez = Script.RunCode(@" return dc % i32; ", context); Assert.Equal(dc % i32, rez); rez = Script.RunCode(@" return dc % i64; ", context); Assert.Equal(dc % i64, rez); rez = Script.RunCode(@" return dc % new decimal(f); ", context); Assert.Equal(dc % new decimal(f), rez); rez = Script.RunCode(@" return dc % new decimal(d); ", context); Assert.Equal(dc % new decimal(d), rez); } } #region Helpers public interface IS { int this[string index] { get; } } public class SQLiteDataReader : IS { #region IS Members int IS.this[string index] { get { return index.Length; } } #endregion } public class EventHelperInvocation { public int test; public event System.EventHandler eva; public bool IsEventNull() { return eva == null; } public void OnEva() { eva.Invoke(this, EventArgs.Empty); } } public class CharValueObject { public char CharValue { get { return 'C'; } } } public class DecimalValueObject { public decimal V1 { get { return 45m; } } public decimal V2 { get { return 5m; } } } #endregion }
using System; using CppSharp.AST; using CppSharp.AST.Extensions; using CppSharp.Generators.C; using CppSharp.Generators.CLI; using CppSharp.Types; using Delegate = CppSharp.AST.Delegate; using Type = CppSharp.AST.Type; namespace CppSharp.Generators.Cpp { public class CppMarshalNativeToManagedPrinter : MarshalPrinter<MarshalContext> { public CppMarshalNativeToManagedPrinter(MarshalContext marshalContext) : base(marshalContext) { } public string MemoryAllocOperator => (Context.Context.Options.GeneratorKind == GeneratorKind.CLI) ? "gcnew" : "new"; public override bool VisitType(Type type, TypeQualifiers quals) { TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling) { typeMap.CppMarshalToManaged(Context); return false; } return true; } public override bool VisitArrayType(ArrayType array, TypeQualifiers quals) { switch (array.SizeType) { case ArrayType.ArraySize.Constant: case ArrayType.ArraySize.Incomplete: case ArrayType.ArraySize.Variable: Context.Return.Write("nullptr"); break; default: throw new System.NotImplementedException(); } return true; } public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals) { Context.Return.Write(Context.ReturnVarName); return true; } public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals) { if (!VisitType(pointer, quals)) return false; var pointee = pointer.Pointee.Desugar(); PrimitiveType primitive; var param = Context.Parameter; if (param != null && (param.IsOut || param.IsInOut) && pointee.IsPrimitiveType(out primitive)) { Context.Return.Write(Context.ReturnVarName); return true; } if (pointee.IsPrimitiveType(out primitive)) { var returnVarName = Context.ReturnVarName; if (pointer.GetFinalQualifiedPointee().Qualifiers.IsConst != Context.ReturnType.Qualifiers.IsConst) { var nativeTypePrinter = new CppTypePrinter(Context.Context) { PrintTypeQualifiers = false }; var returnType = Context.ReturnType.Type.Desugar(); var constlessPointer = new PointerType() { IsDependent = pointer.IsDependent, Modifier = pointer.Modifier, QualifiedPointee = new QualifiedType(returnType.GetPointee()) }; var nativeConstlessTypeName = constlessPointer.Visit(nativeTypePrinter, new TypeQualifiers()); returnVarName = string.Format("const_cast<{0}>({1})", nativeConstlessTypeName, Context.ReturnVarName); } if (pointer.Pointee is TypedefType) { var desugaredPointer = new PointerType() { IsDependent = pointer.IsDependent, Modifier = pointer.Modifier, QualifiedPointee = new QualifiedType(pointee) }; var nativeTypePrinter = new CppTypePrinter(Context.Context); var nativeTypeName = desugaredPointer.Visit(nativeTypePrinter, quals); Context.Return.Write("reinterpret_cast<{0}>({1})", nativeTypeName, returnVarName); } else Context.Return.Write(returnVarName); return true; } TypeMap typeMap = null; Context.Context.TypeMaps.FindTypeMap(pointee, out typeMap); Class @class; if (pointee.TryGetClass(out @class) && typeMap == null) { var instance = (pointer.IsReference) ? "&" + Context.ReturnVarName : Context.ReturnVarName; WriteClassInstance(@class, instance); return true; } return pointer.QualifiedPointee.Visit(this); } public override bool VisitMemberPointerType(MemberPointerType member, TypeQualifiers quals) { return false; } public override bool VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals) { return VisitPrimitiveType(builtin.Type); } public bool VisitPrimitiveType(PrimitiveType primitive) { switch (primitive) { case PrimitiveType.Void: return true; case PrimitiveType.Bool: case PrimitiveType.Char: case PrimitiveType.Char16: case PrimitiveType.WideChar: case PrimitiveType.SChar: case PrimitiveType.UChar: case PrimitiveType.Short: case PrimitiveType.UShort: case PrimitiveType.Int: case PrimitiveType.UInt: case PrimitiveType.Long: case PrimitiveType.ULong: case PrimitiveType.LongLong: case PrimitiveType.ULongLong: case PrimitiveType.Float: case PrimitiveType.Double: case PrimitiveType.LongDouble: case PrimitiveType.Null: Context.Return.Write(Context.ReturnVarName); return true; } throw new NotSupportedException(); } public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals) { var decl = typedef.Declaration; TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(decl.Type, out typeMap) && typeMap.DoesMarshalling) { typeMap.Type = typedef; typeMap.CppMarshalToManaged(Context); return typeMap.IsValueType; } FunctionType function; if (decl.Type.IsPointerTo(out function)) { throw new System.NotImplementedException(); } return decl.Type.Visit(this); } public override bool VisitTemplateSpecializationType(TemplateSpecializationType template, TypeQualifiers quals) { TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(template, out typeMap) && typeMap.DoesMarshalling) { typeMap.Type = template; typeMap.CppMarshalToManaged(Context); return true; } return template.Template.Visit(this); } public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals) { throw new NotImplementedException(); } public override bool VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals) { throw new NotImplementedException(); } public override bool VisitDeclaration(Declaration decl, TypeQualifiers quals) { throw new NotImplementedException(); } public override bool VisitClassDecl(Class @class) { if (@class.CompleteDeclaration != null) return VisitClassDecl(@class.CompleteDeclaration as Class); var instance = string.Empty; if (Context.Context.Options.GeneratorKind == GeneratorKind.CLI) { if (!Context.ReturnType.Type.IsPointer()) instance += "&"; } instance += Context.ReturnVarName; var needsCopy = Context.MarshalKind != MarshalKind.NativeField; if (@class.IsRefType && needsCopy) { var name = Generator.GeneratedIdentifier(Context.ReturnVarName); Context.Before.WriteLine($"auto {name} = {MemoryAllocOperator} ::{{0}}({{1}});", @class.QualifiedOriginalName, Context.ReturnVarName); instance = name; } WriteClassInstance(@class, instance); return true; } public string QualifiedIdentifier(Declaration decl) { if (!string.IsNullOrEmpty(decl.TranslationUnit.Module.OutputNamespace)) return $"{decl.TranslationUnit.Module.OutputNamespace}::{decl.QualifiedName}"; return decl.QualifiedName; } public void WriteClassInstance(Class @class, string instance) { if (!Context.ReturnType.Type.IsPointer()) { Context.Return.Write($"{instance}"); return; } if (@class.IsRefType) Context.Return.Write($"({instance} == nullptr) ? nullptr : {MemoryAllocOperator} "); Context.Return.Write($"{QualifiedIdentifier(@class)}("); Context.Return.Write($"(::{@class.QualifiedOriginalName}*)"); Context.Return.Write($"{instance})"); } public override bool VisitFieldDecl(Field field) { return field.Type.Visit(this); } public override bool VisitFunctionDecl(Function function) { throw new NotImplementedException(); } public override bool VisitMethodDecl(Method method) { throw new NotImplementedException(); } public override bool VisitParameterDecl(Parameter parameter) { Context.Parameter = parameter; var ret = parameter.Type.Visit(this, parameter.QualifiedType.Qualifiers); Context.Parameter = null; return ret; } public override bool VisitTypedefDecl(TypedefDecl typedef) { throw new NotImplementedException(); } public override bool VisitEnumDecl(Enumeration @enum) { var typePrinter = new CppTypePrinter(Context.Context); var typeName = typePrinter.VisitDeclaration(@enum); Context.Return.Write($"({typeName}){Context.ReturnVarName}"); return true; } public override bool VisitVariableDecl(Variable variable) { return variable.Type.Visit(this, variable.QualifiedType.Qualifiers); } public override bool VisitClassTemplateDecl(ClassTemplate template) { return template.TemplatedClass.Visit(this); } public override bool VisitFunctionTemplateDecl(FunctionTemplate template) { return template.TemplatedFunction.Visit(this); } } public class CppMarshalManagedToNativePrinter : MarshalPrinter<MarshalContext> { public readonly TextGenerator VarPrefix; public readonly TextGenerator ArgumentPrefix; public CppMarshalManagedToNativePrinter(MarshalContext ctx) : base(ctx) { VarPrefix = new TextGenerator(); ArgumentPrefix = new TextGenerator(); Context.MarshalToNative = this; } public override bool VisitType(Type type, TypeQualifiers quals) { TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling) { typeMap.CppMarshalToNative(Context); return false; } return true; } public override bool VisitTagType(TagType tag, TypeQualifiers quals) { if (!VisitType(tag, quals)) return false; return tag.Declaration.Visit(this); } public override bool VisitArrayType(ArrayType array, TypeQualifiers quals) { if (!VisitType(array, quals)) return false; switch (array.SizeType) { default: Context.Return.Write("nullptr"); break; } return true; } public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals) { var returnType = function.ReturnType; return returnType.Visit(this); } public bool VisitDelegateType(string type) { Context.Return.Write(Context.Parameter.Name); return true; } public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals) { if (!VisitType(pointer, quals)) return false; var pointee = pointer.Pointee.Desugar(); if (pointee is FunctionType) { var cppTypePrinter = new CppTypePrinter(Context.Context); var cppTypeName = pointer.Visit(cppTypePrinter, quals); return VisitDelegateType(cppTypeName); } Enumeration @enum; if (pointee.TryGetEnum(out @enum)) { var isRef = Context.Parameter.Usage == ParameterUsage.Out || Context.Parameter.Usage == ParameterUsage.InOut; ArgumentPrefix.Write("&"); Context.Return.Write($"(::{@enum.QualifiedOriginalName}){0}{Context.Parameter.Name}", isRef ? string.Empty : "*"); return true; } Class @class; if (pointee.TryGetClass(out @class) && @class.IsValueType) { if (Context.Function == null) Context.Return.Write("&"); return pointer.QualifiedPointee.Visit(this); } var finalPointee = pointer.GetFinalPointee(); if (finalPointee.IsPrimitiveType()) { var cppTypePrinter = new CppTypePrinter(Context.Context); var cppTypeName = pointer.Visit(cppTypePrinter, quals); Context.Return.Write($"({cppTypeName})"); Context.Return.Write(Context.Parameter.Name); return true; } return pointer.QualifiedPointee.Visit(this); } public override bool VisitMemberPointerType(MemberPointerType member, TypeQualifiers quals) { return false; } public override bool VisitBuiltinType(BuiltinType builtin, TypeQualifiers quals) { return VisitPrimitiveType(builtin.Type); } public bool VisitPrimitiveType(PrimitiveType primitive) { switch (primitive) { case PrimitiveType.Void: return true; case PrimitiveType.Bool: case PrimitiveType.Char: case PrimitiveType.UChar: case PrimitiveType.Short: case PrimitiveType.UShort: case PrimitiveType.Int: case PrimitiveType.UInt: case PrimitiveType.Long: case PrimitiveType.ULong: case PrimitiveType.LongLong: case PrimitiveType.ULongLong: case PrimitiveType.Float: case PrimitiveType.Double: case PrimitiveType.WideChar: Context.Return.Write(Context.Parameter.Name); return true; default: throw new NotImplementedException(); } } public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals) { var decl = typedef.Declaration; TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(decl.Type, out typeMap) && typeMap.DoesMarshalling) { typeMap.CppMarshalToNative(Context); return typeMap.IsValueType; } FunctionType func; if (decl.Type.IsPointerTo(out func)) { var typePrinter = new CppTypePrinter(Context.Context); // Use the original typedef name if available, otherwise just use the function pointer type string cppTypeName; if (!decl.IsSynthetized) cppTypeName = "::" + typedef.Declaration.QualifiedOriginalName; else { cppTypeName = decl.Type.Visit(typePrinter, quals); } VisitDelegateType(cppTypeName); return true; } PrimitiveType primitive; if (decl.Type.IsPrimitiveType(out primitive)) { Context.Return.Write($"(::{typedef.Declaration.QualifiedOriginalName})"); } return decl.Type.Visit(this); } public override bool VisitTemplateSpecializationType(TemplateSpecializationType template, TypeQualifiers quals) { TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(template, out typeMap) && typeMap.DoesMarshalling) { typeMap.Type = template; typeMap.CppMarshalToNative(Context); return true; } return template.Template.Visit(this); } public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals) { Context.Return.Write(param.Parameter.Name); return true; } public override bool VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals) { throw new NotImplementedException(); } public override bool VisitDeclaration(Declaration decl, TypeQualifiers quals) { throw new NotImplementedException(); } public override bool VisitClassDecl(Class @class) { if (@class.CompleteDeclaration != null) return VisitClassDecl(@class.CompleteDeclaration as Class); if (@class.IsValueType) { MarshalValueClass(@class); } else { MarshalRefClass(@class); } return true; } private void MarshalRefClass(Class @class) { var type = Context.Parameter.Type.Desugar(); TypeMap typeMap; if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling) { typeMap.CppMarshalToNative(Context); return; } if (!type.SkipPointerRefs().IsPointer()) { Context.Return.Write("*"); if (Context.Parameter.Type.IsReference()) VarPrefix.Write("&"); } var method = Context.Function as Method; if (method != null && method.Conversion == MethodConversionKind.FunctionToInstanceMethod && Context.ParameterIndex == 0) { Context.Return.Write($"(::{@class.QualifiedOriginalName}*)"); Context.Return.Write(Helpers.InstanceIdentifier); return; } var paramType = Context.Parameter.Type.Desugar(); var isPointer = paramType.SkipPointerRefs().IsPointer(); var deref = isPointer ? "->" : "."; var instance = $"(::{@class.QualifiedOriginalName}*)" + $"{Context.Parameter.Name}{deref}{Helpers.InstanceIdentifier}"; if (isPointer) Context.Return.Write($"{Context.Parameter.Name} ? {instance} : nullptr"); else Context.Return.Write($"{instance}"); } private void MarshalValueClass(Class @class) { throw new System.NotImplementedException(); } public override bool VisitFieldDecl(Field field) { Context.Parameter = new Parameter { Name = Context.ArgName, QualifiedType = field.QualifiedType }; return field.Type.Visit(this); } public override bool VisitProperty(Property property) { Context.Parameter = new Parameter { Name = Context.ArgName, QualifiedType = property.QualifiedType }; return base.VisitProperty(property); } public override bool VisitFunctionDecl(Function function) { throw new NotImplementedException(); } public override bool VisitMethodDecl(Method method) { throw new NotImplementedException(); } public override bool VisitParameterDecl(Parameter parameter) { return parameter.Type.Visit(this); } public override bool VisitTypedefDecl(TypedefDecl typedef) { throw new NotImplementedException(); } public override bool VisitEnumDecl(Enumeration @enum) { Context.Return.Write("(::{0}){1}", @enum.QualifiedOriginalName, Context.Parameter.Name); return true; } public override bool VisitVariableDecl(Variable variable) { throw new NotImplementedException(); } public override bool VisitClassTemplateDecl(ClassTemplate template) { return template.TemplatedClass.Visit(this); } public override bool VisitFunctionTemplateDecl(FunctionTemplate template) { return template.TemplatedFunction.Visit(this); } public override bool VisitMacroDefinition(MacroDefinition macro) { throw new NotImplementedException(); } public override bool VisitNamespace(Namespace @namespace) { throw new NotImplementedException(); } public override bool VisitEvent(Event @event) { throw new NotImplementedException(); } public bool VisitDelegate(Delegate @delegate) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.Win32; using NuGet.Configuration; using Cosmos.Build.Installer; namespace Cosmos.Build.Builder { /// <summary> /// Cosmos task. /// </summary> /// <seealso cref="Cosmos.Build.Installer.Task" /> public class CosmosTask : Task { private string mCosmosPath; // Root Cosmos dir private string mVsipPath; // Build/VSIP private string mAppDataPath; // User Kit in AppData private string mSourcePath; // Cosmos source rood private string mInnoPath; private string mInnoFile; private BuildState mBuildState; private int mReleaseNo; private List<string> mExceptionList = new List<string>(); public CosmosTask(string aCosmosDir, int aReleaseNo) { mCosmosPath = aCosmosDir; mVsipPath = Path.Combine(mCosmosPath, @"Build\VSIP"); mSourcePath = Path.Combine(mCosmosPath, "source"); mAppDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Cosmos User Kit"); mReleaseNo = aReleaseNo; mInnoFile = Path.Combine(mCosmosPath, @"Setup\Cosmos.iss"); } /// <summary> /// Get name of the setup file based on release number and the current setting. /// </summary> /// <param name="releaseNumber">Release number for the current setup.</param> /// <returns>Name of the setup file.</returns> public static string GetSetupName(int releaseNumber) { string setupName = $"CosmosUserKit-{releaseNumber}-vs2017"; if (App.UseVsHive) { setupName += "Exp"; } return setupName; } private void CleanDirectory(string aName, string aPath) { if (Directory.Exists(aPath)) { Log.WriteLine("Cleaning up existing " + aName + " directory."); Directory.Delete(aPath, true); } Log.WriteLine("Creating " + aName + " as " + aPath); Directory.CreateDirectory(aPath); } protected override List<string> DoRun() { if (PrereqsOK()) { Section("Init Directories"); CleanDirectory("VSIP", mVsipPath); if (!App.IsUserKit) { CleanDirectory("User Kit", mAppDataPath); } CompileCosmos(); CreateSetup(); if (!App.IsUserKit) { RunSetup(); WriteDevKit(); if (!App.DoNotLaunchVS) { LaunchVS(); } } Done(); } return mExceptionList; } protected void MSBuild(string aSlnFile, string aBuildCfg) { string xMSBuild = Path.Combine(Paths.VSPath, "MSBuild", "15.0", "Bin", "msbuild.exe"); string xParams = $"{Quoted(aSlnFile)} " + "/nologo " + "/maxcpucount " + "/nodeReuse:False " + $"/p:Configuration={Quoted(aBuildCfg)} " + $"/p:Platform={Quoted("Any CPU")} " + $"/p:OutputPath={Quoted(mVsipPath)}"; if (!App.NoMSBuildClean) { StartConsole(xMSBuild, $"/t:Clean {xParams}"); } StartConsole(xMSBuild, $"/t:Build {xParams}"); } protected int NumProcessesContainingName(string name) { return (from x in Process.GetProcesses() where x.ProcessName.Contains(name) select x).Count(); } protected void CheckIfBuilderRunning() { //Check for builder process Log.WriteLine("Check if Builder is running."); // Check > 1 so we exclude ourself. if (NumProcessesContainingName("Cosmos.Build.Builder") > 1) { throw new Exception("Another instance of builder is running."); } } protected void CheckIfUserKitRunning() { Log.WriteLine("Check if User Kit Installer is already running."); if (NumProcessesContainingName("CosmosUserKit") > 0) { throw new Exception("Another instance of the user kit installer is running."); } } protected void CheckIfVSRunning() { int xSeconds = 500; if (Debugger.IsAttached) { Log.WriteLine("Check if Visual Studio is running is ignored by debugging of Builder."); } else { Log.WriteLine("Check if Visual Studio is running."); if (IsRunning("devenv")) { Log.WriteLine("--Visual Studio is running."); Log.WriteLine("--Waiting " + xSeconds + " seconds to see if Visual Studio exits."); // VS doesnt exit right away and user can try devkit again after VS window has closed but is still running. // So we wait a few seconds first. if (WaitForExit("devenv", xSeconds * 1000)) { throw new Exception("Visual Studio is running. Please close it or kill it in task manager."); } } } } protected void NotFound(string aName) { mExceptionList.Add("Prerequisite '" + aName + "' not found."); mBuildState = BuildState.PrerequisiteMissing; } protected bool PrereqsOK() { Section("Check Prerequisites"); CheckIfUserKitRunning(); CheckIfVSRunning(); CheckIfBuilderRunning(); CheckForNetCore(); CheckForVisualStudioExtensionTools(); CheckForInno(); return mBuildState != BuildState.PrerequisiteMissing; } private void CheckForInno() { Log.WriteLine("Check for Inno Setup"); using (var xKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 5_is1", false)) { if (xKey == null) { mExceptionList.Add("Cannot find Inno Setup."); mBuildState = BuildState.PrerequisiteMissing; return; } mInnoPath = (string)xKey.GetValue("InstallLocation"); if (string.IsNullOrWhiteSpace(mInnoPath)) { mExceptionList.Add("Cannot find Inno Setup."); mBuildState = BuildState.PrerequisiteMissing; return; } } Log.WriteLine("Check for Inno Preprocessor"); if (!File.Exists(Path.Combine(mInnoPath, "ISPP.dll"))) { mExceptionList.Add("Inno Preprocessor not detected."); mBuildState = BuildState.PrerequisiteMissing; return; } } private void CheckForNetCore() { Log.WriteLine("Check for .NET Core"); if (!Paths.VSInstancePackages.Contains("Microsoft.VisualStudio.Workload.NetCoreTools")) { mExceptionList.Add(".NET Core not detected."); mBuildState = BuildState.PrerequisiteMissing; } } private void CheckForVisualStudioExtensionTools() { Log.WriteLine("Check for Visual Studio Extension Tools"); if (!Paths.VSInstancePackages.Contains("Microsoft.VisualStudio.Workload.VisualStudioExtension")) { mExceptionList.Add("Visual Studio Extension tools not detected."); mBuildState = BuildState.PrerequisiteMissing; } } private void WriteDevKit() { Section("Write Dev Kit to Registry"); // Inno deletes this from registry, so we must add this after. // We let Inno delete it, so if user runs it by itself they get // only UserKit, and no DevKit settings. // HKCU instead of HKLM because builder does not run as admin. // // HKCU is not redirected. using (var xKey = Registry.CurrentUser.CreateSubKey(@"Software\Cosmos")) { xKey.SetValue("DevKit", mCosmosPath); } } private void Clean(string project) { string xNuget = Path.Combine(mCosmosPath, "Build", "Tools", "nuget.exe"); string xListParams = $"sources List"; StartConsole(xNuget, xListParams); var xStart = new ProcessStartInfo(); xStart.FileName = xNuget; xStart.WorkingDirectory = CurrPath; xStart.Arguments = xListParams; xStart.UseShellExecute = false; xStart.CreateNoWindow = true; xStart.RedirectStandardOutput = true; xStart.RedirectStandardError = true; using (var xProcess = Process.Start(xStart)) { using (var xReader = xProcess.StandardOutput) { string xLine; while (true) { xLine = xReader.ReadLine(); if (xLine == null) { break; } if (xLine.Contains("Cosmos Local Package Feed")) { string xUninstallParams = $"sources Remove -Name \"Cosmos Local Package Feed\""; StartConsole(xNuget, xUninstallParams); } } } } // Clean Cosmos packages from NuGet cache var xGlobalFolder = SettingsUtility.GetGlobalPackagesFolder(Settings.LoadDefaultSettings(Environment.SystemDirectory)); // Later we should specify the packages, currently we're moving to gen3 so package names are a bit unstable foreach (var xFolder in Directory.EnumerateDirectories(xGlobalFolder)) { if (new DirectoryInfo(xFolder).Name.StartsWith("Cosmos", StringComparison.InvariantCultureIgnoreCase)) { CleanPackage(xFolder); } } void CleanPackage(string aPackage) { var xPath = Path.Combine(xGlobalFolder, aPackage); if (Directory.Exists(xPath)) { Directory.Delete(xPath, true); } } } private void Restore(string project) { string xNuget = Path.Combine(mCosmosPath, "Build", "Tools", "nuget.exe"); string xRestoreParams = $"restore {Quoted(project)}"; StartConsole(xNuget, xRestoreParams); } private void Update() { string xNuget = Path.Combine(mCosmosPath, "Build", "Tools", "nuget.exe"); string xUpdateParams = $"update -self"; StartConsole(xNuget, xUpdateParams); } private void Pack(string project, string destDir) { string xMSBuild = Path.Combine(Paths.VSPath, "MSBuild", "15.0", "Bin", "msbuild.exe"); string xParams = $"{Quoted(project)} /nodeReuse:False /t:Restore;Pack /maxcpucount /p:PackageOutputPath={Quoted(destDir)}"; StartConsole(xMSBuild, xParams); } private void Publish(string project, string destDir) { string xMSBuild = Path.Combine(Paths.VSPath, "MSBuild", "15.0", "Bin", "msbuild.exe"); string xParams = $"{Quoted(project)} /nodeReuse:False /t:Publish /maxcpucount /p:RuntimeIdentifier=win7-x86 /p:PublishDir={Quoted(destDir)}"; StartConsole(xMSBuild, xParams); } private void CompileCosmos() { string xVsipDir = Path.Combine(mCosmosPath, "Build", "VSIP"); string xNugetPkgDir = Path.Combine(xVsipDir, "KernelPackages"); Section("Clean NuGet Local Feed"); Clean(Path.Combine(mCosmosPath, @"Build.sln")); Section("Restore NuGet Packages"); Restore(Path.Combine(mCosmosPath, @"Build.sln")); Restore(Path.Combine(mCosmosPath, @"../IL2CPU/IL2CPU.sln")); Restore(Path.Combine(mCosmosPath, @"../XSharp/XSharp.sln")); Section("Update NuGet"); Update(); Section("Build Cosmos"); // Build.sln is the old master but because of how VS manages refs, we have to hack // this short term with the new slns. MSBuild(Path.Combine(mCosmosPath, @"Build.sln"), "Debug"); Section("Publish Tools"); Publish(Path.Combine(mSourcePath, "Cosmos.Build.MSBuild"), Path.Combine(xVsipDir, "MSBuild")); Publish(Path.Combine(mSourcePath, "../../IL2CPU/source/IL2CPU"), Path.Combine(xVsipDir, "IL2CPU")); Publish(Path.Combine(mCosmosPath, "Tools", "NASM"), Path.Combine(xVsipDir, "NASM")); Section("Pack Kernel"); // Pack(Path.Combine(mSourcePath, "Cosmos.Common"), xNugetPkgDir); // Pack(Path.Combine(mSourcePath, "Cosmos.Core"), xNugetPkgDir); Pack(Path.Combine(mSourcePath, "Cosmos.Core_Plugs"), xNugetPkgDir); Pack(Path.Combine(mSourcePath, "Cosmos.Core_Asm"), xNugetPkgDir); // Pack(Path.Combine(mSourcePath, "Cosmos.HAL2"), xNugetPkgDir); // Pack(Path.Combine(mSourcePath, "Cosmos.System2"), xNugetPkgDir); Pack(Path.Combine(mSourcePath, "Cosmos.System2_Plugs"), xNugetPkgDir); // Pack(Path.Combine(mSourcePath, "Cosmos.Debug.Kernel"), xNugetPkgDir); Pack(Path.Combine(mSourcePath, "Cosmos.Debug.Kernel.Plugs.Asm"), xNugetPkgDir); // Pack(Path.Combine(mSourcePath, "../../IL2CPU/source/Cosmos.IL2CPU.API"), xNugetPkgDir); } private void CopyTemplates() { Section("Copy Templates"); using (var x = new FileMgr(Path.Combine(mSourcePath, @"Cosmos.VS.Package\obj\Debug"), mVsipPath)) { x.Copy("CosmosProject (C#).zip"); x.Copy("CosmosKernel (C#).zip"); x.Copy("CosmosProject (F#).zip"); x.Copy("Cosmos.zip"); x.Copy("CosmosProject (VB).zip"); x.Copy("CosmosKernel (VB).zip"); x.Copy(mSourcePath + @"XSharp.VS\Template\XSharpFileItem.zip"); } } private void CreateSetup() { Section("Creating Setup"); string xISCC = Path.Combine(mInnoPath, "ISCC.exe"); if (!File.Exists(xISCC)) { mExceptionList.Add("Cannot find Inno setup."); return; } string xCfg = App.IsUserKit ? "UserKit" : "DevKit"; string vsVersionConfiguration = "vs2017"; // Use configuration which will install to the VS Exp Hive if (App.UseVsHive) { vsVersionConfiguration += "Exp"; } Log.WriteLine($" {xISCC} /Q {Quoted(mInnoFile)} /dBuildConfiguration={xCfg} /dVSVersion={vsVersionConfiguration} /dChangeSetVersion={Quoted(mReleaseNo.ToString())}"); StartConsole(xISCC, $"/Q {Quoted(mInnoFile)} /dBuildConfiguration={xCfg} /dVSVersion={vsVersionConfiguration} /dChangeSetVersion={Quoted(mReleaseNo.ToString())}"); } private void LaunchVS() { Section("Launching Visual Studio"); string xVisualStudio = Path.Combine(Paths.VSPath, "Common7", "IDE", "devenv.exe"); if (!File.Exists(xVisualStudio)) { mExceptionList.Add("Cannot find Visual Studio."); return; } if (App.ResetHive) { Log.WriteLine("Resetting hive"); Start(xVisualStudio, @"/setup /rootsuffix Exp /ranu"); } Log.WriteLine("Launching Visual Studio"); Start(xVisualStudio, Quoted(mCosmosPath + @"Kernel.sln"), false, true); } private void RunSetup() { Section("Running Setup"); // These cache in RAM which cause problems, so we kill them if present. KillProcesses("dotnet"); KillProcesses("msbuild"); string setupName = GetSetupName(mReleaseNo); Start(mCosmosPath + @"Setup\Output\" + setupName + ".exe", @"/SILENT"); } private void Done() { Section("Build Complete!"); } } }
/* * Licensed to the Apache Software Foundation (ASF) Under one or more * contributor license agreements. See the NOTICE file distributed with * this work for Additional information regarding copyright ownership. * The ASF licenses this file to You Under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed Under the License is distributed on an "AS Is" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations Under the License. */ /* * Created on May 30, 2005 * */ namespace NPOI.SS.Formula.Functions { using NPOI.Util; using System; /** * @author Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt; * * Library for common statistics functions */ internal class StatsLib { private StatsLib() { } /** * returns the mean of deviations from mean. * @param v */ public static double avedev(double[] v) { double r = 0; double m = 0; double s = 0; for (int i = 0, iSize = v.Length; i < iSize; i++) { s += v[i]; } m = s / v.Length; s = 0; for (int i = 0, iSize = v.Length; i < iSize; i++) { s += Math.Abs(v[i] - m); } r = s / v.Length; return r; } public static double stdev(double[] v) { double r = double.NaN; if (v != null && v.Length > 1) { r = Math.Sqrt(devsq(v) / (v.Length - 1)); } return r; } public static double var(double[] v) { double r = Double.NaN; if (v != null && v.Length > 1) { r = devsq(v) / (v.Length - 1); } return r; } public static double varp(double[] v) { double r = Double.NaN; if (v != null && v.Length > 1) { r = devsq(v) / v.Length; } return r; } /** * if v Is zero Length or Contains no duplicates, return value * Is double.NaN. Else returns the value that occurs most times * and if there Is a tie, returns the first such value. * @param v */ public static double mode(double[] v) { double r = double.NaN; // very naive impl, may need to be optimized if (v != null && v.Length > 1) { int[] Counts = new int[v.Length]; Arrays.Fill(Counts, 1); for (int i = 0, iSize = v.Length; i < iSize; i++) { for (int j = i + 1, jSize = v.Length; j < jSize; j++) { if (v[i] == v[j]) Counts[i]++; } } double maxv = 0; int maxc = 0; for (int i = 0, iSize = Counts.Length; i < iSize; i++) { if (Counts[i] > maxc) { maxv = v[i]; maxc = Counts[i]; } } r = (maxc > 1) ? maxv : double.NaN; // "no-dups" Check } return r; } public static double median(double[] v) { double r = double.NaN; if (v != null && v.Length >= 1) { int n = v.Length; Array.Sort(v); r = (n % 2 == 0) ? (v[n / 2] + v[n / 2 - 1]) / 2 : v[n / 2]; } return r; } public static double devsq(double[] v) { double r = double.NaN; if (v != null && v.Length >= 1) { double m = 0; double s = 0; int n = v.Length; for (int i = 0; i < n; i++) { s += v[i]; } m = s / n; s = 0; for (int i = 0; i < n; i++) { s += (v[i] - m) * (v[i] - m); } r = (n == 1) ? 0 : s; } return r; } /* * returns the kth largest element in the array. Duplicates * are considered as distinct values. Hence, eg. * for array {1,2,4,3,3} & k=2, returned value Is 3. * <br/> * k <= 0 & k >= v.Length and null or empty arrays * will result in return value double.NaN * @param v * @param k */ public static double kthLargest(double[] v, int k) { double r = double.NaN; k--; // since arrays are 0-based if (v != null && v.Length > k && k >= 0) { Array.Sort(v); r = v[v.Length - k - 1]; } return r; } /* * returns the kth smallest element in the array. Duplicates * are considered as distinct values. Hence, eg. * for array {1,1,2,4,3,3} & k=2, returned value Is 1. * <br/> * k <= 0 & k >= v.Length or null array or empty array * will result in return value double.NaN * @param v * @param k */ public static double kthSmallest(double[] v, int k) { double r = double.NaN; k--; // since arrays are 0-based if (v != null && v.Length > k && k >= 0) { Array.Sort(v); r = v[k]; } return r; } } }
// 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. namespace System.Resources { using System; using System.IO; using System.Globalization; using System.Collections; using System.Text; using System.Threading; using System.Collections.Generic; using System.Diagnostics; public sealed class ResourceReader : IDisposable { private const int ResSetVersion = 2; private const int ResourceTypeCodeString = 1; private const int ResourceManagerMagicNumber = unchecked((int)0xBEEFCACE); private const int ResourceManagerHeaderVersionNumber = 1; private BinaryReader _store; // backing store we're reading from. private long _nameSectionOffset; // Offset to name section of file. private long _dataSectionOffset; // Offset to Data section of file. private int[] _namePositions; // relative locations of names private Type[] _typeTable; // Lazy array of Types for resource values. private int[] _typeNamePositions; // To delay initialize type table private int _numResources; // Num of resources files, in case arrays aren't allocated. private int _version; public ResourceReader(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (!stream.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable); _store = new BinaryReader(stream, Encoding.UTF8); ReadResources(); } public void Dispose() { Dispose(true); } [System.Security.SecuritySafeCritical] // auto-generated private unsafe void Dispose(bool disposing) { if (_store != null) { if (disposing) { // Close the stream in a thread-safe way. This fix means // that we may call Close n times, but that's safe. BinaryReader copyOfStore = _store; _store = null; if (copyOfStore != null) copyOfStore.Dispose(); } _store = null; _namePositions = null; } } private void SkipString() { int stringLength = Read7BitEncodedInt(); if (stringLength < 0) { throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength); } _store.BaseStream.Seek(stringLength, SeekOrigin.Current); } private unsafe int GetNamePosition(int index) { Debug.Assert(index >= 0 && index < _numResources, "Bad index into name position array. index: " + index); int r; r = _namePositions[index]; if (r < 0 || r > _dataSectionOffset - _nameSectionOffset) { throw new FormatException(SR.BadImageFormat_ResourcesNameInvalidOffset + ":" + r); } return r; } public IDictionaryEnumerator GetEnumerator() { if (_store == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed); return new ResourceEnumerator(this); } private unsafe String AllocateStringForNameIndex(int index, out int dataOffset) { Debug.Assert(_store != null, "ResourceReader is closed!"); byte[] bytes; int byteLen; long nameVA = GetNamePosition(index); lock (this) { _store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin); // Can't use _store.ReadString, since it's using UTF-8! byteLen = Read7BitEncodedInt(); if (byteLen < 0) { throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength); } bytes = new byte[byteLen]; // We must read byteLen bytes, or we have a corrupted file. // Use a blocking read in case the stream doesn't give us back // everything immediately. int count = byteLen; while (count > 0) { int n = _store.Read(bytes, byteLen - count, count); if (n == 0) throw new EndOfStreamException(SR.BadImageFormat_ResourceNameCorrupted_NameIndex + index); count -= n; } dataOffset = _store.ReadInt32(); if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(SR.BadImageFormat_ResourcesDataInvalidOffset + " offset :" + dataOffset); } } return Encoding.Unicode.GetString(bytes, 0, byteLen); } private string GetValueForNameIndex(int index) { Debug.Assert(_store != null, "ResourceReader is closed!"); long nameVA = GetNamePosition(index); lock (this) { _store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin); SkipString(); int dataPos = _store.ReadInt32(); if (dataPos < 0 || dataPos >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(SR.BadImageFormat_ResourcesDataInvalidOffset + dataPos); } try { return LoadString(dataPos); } catch (EndOfStreamException eof) { throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, eof); } catch (ArgumentOutOfRangeException e) { throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, e); } } } //returns null if the resource is not a string private string LoadString(int pos) { _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); int typeIndex = Read7BitEncodedInt(); if (_version == 1) { Type typeinStream = FindType(typeIndex); if (typeIndex == -1 || !typeinStream.Equals(typeof(String))) return null; } else { if (ResourceTypeCodeString != typeIndex) { return null; } } return _store.ReadString(); } private void ReadResources() { Debug.Assert(_store != null, "ResourceReader is closed!"); try { // mega try-catch performs exceptionally bad on x64; factored out body into // _ReadResources and wrap here. _ReadResources(); } catch (EndOfStreamException eof) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, eof); } catch (IndexOutOfRangeException e) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, e); } } private void _ReadResources() { // Read out the ResourceManager header // Read out magic number int magicNum = _store.ReadInt32(); if (magicNum != ResourceManagerMagicNumber) throw new ArgumentException(SR.Resources_StreamNotValid); // Assuming this is ResourceManager header V1 or greater, hopefully // after the version number there is a number of bytes to skip // to bypass the rest of the ResMgr header. For V2 or greater, we // use this to skip to the end of the header int resMgrHeaderVersion = _store.ReadInt32(); //number of bytes to skip over to get past ResMgr header int numBytesToSkip = _store.ReadInt32(); if (numBytesToSkip < 0 || resMgrHeaderVersion < 0) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } if (resMgrHeaderVersion > 1) { _store.BaseStream.Seek(numBytesToSkip, SeekOrigin.Current); } else { // We don't care about numBytesToSkip; read the rest of the header //Due to legacy : this field is always a variant of System.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; //So we Skip the type name for resourcereader unlike Desktop SkipString(); // Skip over type name for a suitable ResourceSet SkipString(); } // Read RuntimeResourceSet header // Do file version check int version = _store.ReadInt32(); if (version != ResSetVersion && version != 1) throw new ArgumentException(SR.Arg_ResourceFileUnsupportedVersion + "Expected:" + ResSetVersion + "but got:" + version); _version = version; // number of resources _numResources = _store.ReadInt32(); if (_numResources < 0) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } // Read type positions into type positions array. // But delay initialize the type table. int numTypes = _store.ReadInt32(); if (numTypes < 0) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } _typeTable = new Type[numTypes]; _typeNamePositions = new int[numTypes]; for (int i = 0; i < numTypes; i++) { _typeNamePositions[i] = (int)_store.BaseStream.Position; // Skip over the Strings in the file. Don't create types. SkipString(); } // Prepare to read in the array of name hashes // Note that the name hashes array is aligned to 8 bytes so // we can use pointers into it on 64 bit machines. (4 bytes // may be sufficient, but let's plan for the future) // Skip over alignment stuff. All public .resources files // should be aligned No need to verify the byte values. long pos = _store.BaseStream.Position; int alignBytes = ((int)pos) & 7; if (alignBytes != 0) { for (int i = 0; i < 8 - alignBytes; i++) { _store.ReadByte(); } } //Skip over the array of name hashes for (int i = 0; i < _numResources; i++) { _store.ReadInt32(); } // Read in the array of relative positions for all the names. _namePositions = new int[_numResources]; for (int i = 0; i < _numResources; i++) { int namePosition = _store.ReadInt32(); if (namePosition < 0) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } _namePositions[i] = namePosition; } // Read location of data section. _dataSectionOffset = _store.ReadInt32(); if (_dataSectionOffset < 0) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } // Store current location as start of name section _nameSectionOffset = _store.BaseStream.Position; // _nameSectionOffset should be <= _dataSectionOffset; if not, it's corrupt if (_dataSectionOffset < _nameSectionOffset) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } } private Type FindType(int typeIndex) { if (typeIndex < 0 || typeIndex >= _typeTable.Length) { throw new BadImageFormatException(SR.BadImageFormat_InvalidType); } if (_typeTable[typeIndex] == null) { long oldPos = _store.BaseStream.Position; try { _store.BaseStream.Position = _typeNamePositions[typeIndex]; String typeName = _store.ReadString(); _typeTable[typeIndex] = Type.GetType(typeName, true); } finally { _store.BaseStream.Position = oldPos; } } Debug.Assert(_typeTable[typeIndex] != null, "Should have found a type!"); return _typeTable[typeIndex]; } //blatantly copied over from BinaryReader private int Read7BitEncodedInt() { // Read out an Int32 7 bits at a time. The high bit // of the byte when on means to continue reading more bytes. int count = 0; int shift = 0; byte b; do { // Check for a corrupted stream. Read a max of 5 bytes. // In a future version, add a DataFormatException. if (shift == 5 * 7) // 5 bytes max per Int32, shift += 7 throw new FormatException(SR.Format_Bad7BitInt32); // ReadByte handles end of stream cases for us. b = _store.ReadByte(); count |= (b & 0x7F) << shift; shift += 7; } while ((b & 0x80) != 0); return count; } internal sealed class ResourceEnumerator : IDictionaryEnumerator { private const int ENUM_DONE = Int32.MinValue; private const int ENUM_NOT_STARTED = -1; private ResourceReader _reader; private bool _currentIsValid; private int _currentName; internal ResourceEnumerator(ResourceReader reader) { _currentName = ENUM_NOT_STARTED; _reader = reader; } public bool MoveNext() { if (_currentName == _reader._numResources - 1 || _currentName == ENUM_DONE) { _currentIsValid = false; _currentName = ENUM_DONE; return false; } _currentIsValid = true; _currentName++; return true; } public Object Key { [System.Security.SecuritySafeCritical] // auto-generated get { if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); int _dataPosition; return _reader.AllocateStringForNameIndex(_currentName, out _dataPosition); } } public Object Current { get { return Entry; } } public DictionaryEntry Entry { [System.Security.SecuritySafeCritical] // auto-generated get { if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); String key; Object value = null; int _dataPosition; key = _reader.AllocateStringForNameIndex(_currentName, out _dataPosition); value = _reader.GetValueForNameIndex(_currentName); return new DictionaryEntry(key, value); } } public Object Value { get { if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); return _reader.GetValueForNameIndex(_currentName); } } public void Reset() { if (_reader._store == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed); _currentIsValid = false; _currentName = ENUM_NOT_STARTED; } } } }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/> // <version>$Revision: 3660 $</version> // </file> using System; using ICSharpCode.NRefactory.Ast; namespace ICSharpCode.NRefactory.Visitors { /// <summary> /// Converts elements not supported by C# to their C# representation. /// Not all elements are converted here, most simple elements (e.g. StopStatement) /// are converted in the output visitor. /// </summary> public class ToCSharpConvertVisitor : ConvertVisitorBase { // The following conversions are implemented: // Public Event EventName(param As String) -> automatic delegate declaration // static variables inside methods become fields // Explicit interface implementation: // => create additional member for implementing the interface // or convert to implicit interface implementation // Modules: make all members static public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data) { if (typeDeclaration.Type == ClassType.Module) { typeDeclaration.Type = ClassType.Class; typeDeclaration.Modifier |= Modifiers.Static; foreach (INode node in typeDeclaration.Children) { MemberNode aNode = node as MemberNode; if (aNode != null) { aNode.Modifier |= Modifiers.Static; } FieldDeclaration fd = node as FieldDeclaration; if (fd != null) { if ((fd.Modifier & Modifiers.Const) == 0) fd.Modifier |= Modifiers.Static; } } } return base.VisitTypeDeclaration(typeDeclaration, data); } public override object VisitEventDeclaration(EventDeclaration eventDeclaration, object data) { if (!eventDeclaration.HasAddRegion && !eventDeclaration.HasRaiseRegion && !eventDeclaration.HasRemoveRegion) { if (eventDeclaration.TypeReference.IsNull) { DelegateDeclaration dd = new DelegateDeclaration(eventDeclaration.Modifier, null); dd.Name = eventDeclaration.Name + "EventHandler"; dd.Parameters = eventDeclaration.Parameters; dd.ReturnType = new TypeReference("System.Void", true); dd.Parent = eventDeclaration.Parent; eventDeclaration.Parameters = null; InsertAfterSibling(eventDeclaration, dd); eventDeclaration.TypeReference = new TypeReference(dd.Name); } } return base.VisitEventDeclaration(eventDeclaration, data); } public override object VisitMethodDeclaration(MethodDeclaration md, object data) { ConvertInterfaceImplementation(md); return base.VisitMethodDeclaration(md, data); } void ConvertInterfaceImplementation(MethodDeclaration member) { // members without modifiers are already C# explicit interface implementations, do not convert them if (member.Modifier == Modifiers.None) return; while (member.InterfaceImplementations.Count > 0) { InterfaceImplementation impl = member.InterfaceImplementations[0]; member.InterfaceImplementations.RemoveAt(0); if (member.Name != impl.MemberName) { MethodDeclaration newMember = new MethodDeclaration { Name = impl.MemberName, TypeReference = member.TypeReference, Parameters = member.Parameters, Body = new BlockStatement() }; InvocationExpression callExpression = new InvocationExpression(new IdentifierExpression(member.Name)); foreach (ParameterDeclarationExpression decl in member.Parameters) { callExpression.Arguments.Add(new IdentifierExpression(decl.ParameterName)); } if (member.TypeReference.Type == "System.Void") { newMember.Body.AddChild(new ExpressionStatement(callExpression)); } else { newMember.Body.AddChild(new ReturnStatement(callExpression)); } newMember.InterfaceImplementations.Add(impl); InsertAfterSibling(member, newMember); } } } public override object VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data) { ConvertInterfaceImplementation(propertyDeclaration); return base.VisitPropertyDeclaration(propertyDeclaration, data); } void ConvertInterfaceImplementation(PropertyDeclaration member) { // members without modifiers are already C# explicit interface implementations, do not convert them if (member.Modifier == Modifiers.None) return; while (member.InterfaceImplementations.Count > 0) { InterfaceImplementation impl = member.InterfaceImplementations[0]; member.InterfaceImplementations.RemoveAt(0); if (member.Name != impl.MemberName) { PropertyDeclaration newMember = new PropertyDeclaration(Modifiers.None, null, impl.MemberName, null); newMember.TypeReference = member.TypeReference; if (member.HasGetRegion) { newMember.GetRegion = new PropertyGetRegion(new BlockStatement(), null); newMember.GetRegion.Block.AddChild(new ReturnStatement(new IdentifierExpression(member.Name))); } if (member.HasSetRegion) { newMember.SetRegion = new PropertySetRegion(new BlockStatement(), null); newMember.SetRegion.Block.AddChild(new ExpressionStatement( new AssignmentExpression( new IdentifierExpression(member.Name), AssignmentOperatorType.Assign, new IdentifierExpression("value") ))); } newMember.Parameters = member.Parameters; newMember.InterfaceImplementations.Add(impl); InsertAfterSibling(member, newMember); } } } public override object VisitLocalVariableDeclaration(LocalVariableDeclaration lvd, object data) { base.VisitLocalVariableDeclaration(lvd, data); if ((lvd.Modifier & Modifiers.Static) == Modifiers.Static) { INode parent = lvd.Parent; while (parent != null && !IsTypeLevel(parent)) { parent = parent.Parent; } if (parent != null) { INode type = parent.Parent; if (type != null) { int pos = type.Children.IndexOf(parent); if (pos >= 0) { FieldDeclaration field = new FieldDeclaration(null); field.TypeReference = lvd.TypeReference; field.Modifier = Modifiers.Static; field.Fields = lvd.Variables; new PrefixFieldsVisitor(field.Fields, "static_" + GetTypeLevelEntityName(parent) + "_").Run(parent); type.Children.Insert(pos + 1, field); RemoveCurrentNode(); } } } } return null; } public override object VisitWithStatement(WithStatement withStatement, object data) { withStatement.Body.AcceptVisitor(new ReplaceWithAccessTransformer(withStatement.Expression), data); base.VisitWithStatement(withStatement, data); ReplaceCurrentNode(withStatement.Body); return null; } sealed class ReplaceWithAccessTransformer : AbstractAstTransformer { readonly Expression replaceWith; public ReplaceWithAccessTransformer(Expression replaceWith) { this.replaceWith = replaceWith; } public override object VisitMemberReferenceExpression(MemberReferenceExpression fieldReferenceExpression, object data) { if (fieldReferenceExpression.TargetObject.IsNull) { fieldReferenceExpression.TargetObject = replaceWith; return null; } else { return base.VisitMemberReferenceExpression(fieldReferenceExpression, data); } } public override object VisitWithStatement(WithStatement withStatement, object data) { // do not visit the body of the WithStatement return withStatement.Expression.AcceptVisitor(this, data); } } static bool IsTypeLevel(INode node) { return node is MethodDeclaration || node is PropertyDeclaration || node is EventDeclaration || node is OperatorDeclaration || node is FieldDeclaration; } static string GetTypeLevelEntityName(INode node) { if (node is ParametrizedNode) return ((ParametrizedNode)node).Name; else if (node is FieldDeclaration) return ((FieldDeclaration)node).Fields[0].Name; else throw new ArgumentException(); } public override object VisitSwitchSection(SwitchSection switchSection, object data) { // Check if a 'break' should be auto inserted. if (switchSection.Children.Count == 0 || !(switchSection.Children[switchSection.Children.Count - 1] is BreakStatement || switchSection.Children[switchSection.Children.Count - 1] is ContinueStatement || switchSection.Children[switchSection.Children.Count - 1] is ThrowStatement || switchSection.Children[switchSection.Children.Count - 1] is ReturnStatement)) { switchSection.Children.Add(new BreakStatement()); } return base.VisitSwitchSection(switchSection, data); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Benchmarks; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Data.Shortable; using QuantConnect.Interfaces; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using QuantConnect.Orders.Fills; using QuantConnect.Orders.Slippage; using QuantConnect.Securities; using QuantConnect.Securities.Equity; using QuantConnect.Securities.Future; using QuantConnect.Securities.Option; using QuantConnect.Util; namespace QuantConnect.Brokerages { /// <summary> /// Provides a default implementation of <see cref="IBrokerageModel"/> that allows all orders and uses /// the default transaction models /// </summary> public class DefaultBrokerageModel : IBrokerageModel { /// <summary> /// The default markets for the backtesting brokerage /// </summary> public static readonly IReadOnlyDictionary<SecurityType, string> DefaultMarketMap = new Dictionary<SecurityType, string> { {SecurityType.Base, Market.USA}, {SecurityType.Equity, Market.USA}, {SecurityType.Option, Market.USA}, {SecurityType.Future, Market.CME}, {SecurityType.FutureOption, Market.CME}, {SecurityType.Forex, Market.Oanda}, {SecurityType.Cfd, Market.FXCM}, {SecurityType.Crypto, Market.GDAX}, {SecurityType.Index, Market.USA}, {SecurityType.IndexOption, Market.USA} }.ToReadOnlyDictionary(); /// <summary> /// Determines whether the asset you want to short is shortable. /// The default is set to <see cref="NullShortableProvider"/>, /// which allows for infinite shorting of any asset. You can limit the /// quantity you can short for an asset class by setting this variable to /// your own implementation of <see cref="IShortableProvider"/>. /// </summary> protected IShortableProvider ShortableProvider { get; set; } /// <summary> /// Gets or sets the account type used by this model /// </summary> public virtual AccountType AccountType { get; private set; } /// <summary> /// Gets the brokerages model percentage factor used to determine the required unused buying power for the account. /// From 1 to 0. Example: 0 means no unused buying power is required. 0.5 means 50% of the buying power should be left unused. /// </summary> public virtual decimal RequiredFreeBuyingPowerPercent => 0m; /// <summary> /// Gets a map of the default markets to be used for each security type /// </summary> public virtual IReadOnlyDictionary<SecurityType, string> DefaultMarkets { get { return DefaultMarketMap; } } /// <summary> /// Initializes a new instance of the <see cref="DefaultBrokerageModel"/> class /// </summary> /// <param name="accountType">The type of account to be modelled, defaults to /// <see cref="QuantConnect.AccountType.Margin"/></param> public DefaultBrokerageModel(AccountType accountType = AccountType.Margin) { AccountType = accountType; // Shortable provider, responsible for loading the data that indicates how much // quantity we can short for a given asset. The NullShortableProvider default will // allow for infinite quantities of any asset to be shorted. ShortableProvider = new NullShortableProvider(); } /// <summary> /// Returns true if the brokerage could accept this order. This takes into account /// order type, security type, and order size limits. /// </summary> /// <remarks> /// For example, a brokerage may have no connectivity at certain times, or an order rate/size limit /// </remarks> /// <param name="security">The security being ordered</param> /// <param name="order">The order to be processed</param> /// <param name="message">If this function returns false, a brokerage message detailing why the order may not be submitted</param> /// <returns>True if the brokerage could process the order, false otherwise</returns> public virtual bool CanSubmitOrder(Security security, Order order, out BrokerageMessageEvent message) { message = null; return true; } /// <summary> /// Returns true if the brokerage would allow updating the order as specified by the request /// </summary> /// <param name="security">The security of the order</param> /// <param name="order">The order to be updated</param> /// <param name="request">The requested update to be made to the order</param> /// <param name="message">If this function returns false, a brokerage message detailing why the order may not be updated</param> /// <returns>True if the brokerage would allow updating the order, false otherwise</returns> public virtual bool CanUpdateOrder(Security security, Order order, UpdateOrderRequest request, out BrokerageMessageEvent message) { message = null; return true; } /// <summary> /// Returns true if the brokerage would be able to execute this order at this time assuming /// market prices are sufficient for the fill to take place. This is used to emulate the /// brokerage fills in backtesting and paper trading. For example some brokerages may not perform /// executions during extended market hours. This is not intended to be checking whether or not /// the exchange is open, that is handled in the Security.Exchange property. /// </summary> /// <param name="security">The security being traded</param> /// <param name="order">The order to test for execution</param> /// <returns>True if the brokerage would be able to perform the execution, false otherwise</returns> public virtual bool CanExecuteOrder(Security security, Order order) { return true; } /// <summary> /// Applies the split to the specified order ticket /// </summary> /// <remarks> /// This default implementation will update the orders to maintain a similar market value /// </remarks> /// <param name="tickets">The open tickets matching the split event</param> /// <param name="split">The split event data</param> public virtual void ApplySplit(List<OrderTicket> tickets, Split split) { // by default we'll just update the orders to have the same notional value var splitFactor = split.SplitFactor; tickets.ForEach(ticket => ticket.Update(new UpdateOrderFields { Quantity = (int?) (ticket.Quantity/splitFactor), LimitPrice = ticket.OrderType.IsLimitOrder() ? ticket.Get(OrderField.LimitPrice)*splitFactor : (decimal?) null, StopPrice = ticket.OrderType.IsStopOrder() ? ticket.Get(OrderField.StopPrice)*splitFactor : (decimal?) null })); } /// <summary> /// Gets the brokerage's leverage for the specified security /// </summary> /// <param name="security">The security's whose leverage we seek</param> /// <returns>The leverage for the specified security</returns> public virtual decimal GetLeverage(Security security) { if (AccountType == AccountType.Cash) { return 1m; } switch (security.Type) { case SecurityType.Equity: return 2m; case SecurityType.Forex: case SecurityType.Cfd: return 50m; case SecurityType.Crypto: return 1m; case SecurityType.Base: case SecurityType.Commodity: case SecurityType.Option: case SecurityType.FutureOption: case SecurityType.Future: case SecurityType.Index: case SecurityType.IndexOption: default: return 1m; } } /// <summary> /// Get the benchmark for this model /// </summary> /// <param name="securities">SecurityService to create the security with if needed</param> /// <returns>The benchmark for this brokerage</returns> public virtual IBenchmark GetBenchmark(SecurityManager securities) { var symbol = Symbol.Create("SPY", SecurityType.Equity, Market.USA); return SecurityBenchmark.CreateInstance(securities, symbol); } /// <summary> /// Gets a new fill model that represents this brokerage's fill behavior /// </summary> /// <param name="security">The security to get fill model for</param> /// <returns>The new fill model for this brokerage</returns> public virtual IFillModel GetFillModel(Security security) { switch (security.Type) { case SecurityType.Base: break; case SecurityType.Equity: return new EquityFillModel(); case SecurityType.Option: break; case SecurityType.FutureOption: break; case SecurityType.Commodity: break; case SecurityType.Forex: break; case SecurityType.Future: break; case SecurityType.Cfd: break; case SecurityType.Crypto: break; case SecurityType.Index: break; case SecurityType.IndexOption: break; default: throw new ArgumentOutOfRangeException($"{GetType().Name}.GetFillModel: Invalid security type {security.Type}"); } return new ImmediateFillModel(); } /// <summary> /// Gets a new fee model that represents this brokerage's fee structure /// </summary> /// <param name="security">The security to get a fee model for</param> /// <returns>The new fee model for this brokerage</returns> public virtual IFeeModel GetFeeModel(Security security) { switch (security.Type) { case SecurityType.Base: case SecurityType.Forex: case SecurityType.Cfd: case SecurityType.Crypto: case SecurityType.Index: return new ConstantFeeModel(0m); case SecurityType.Equity: case SecurityType.Option: case SecurityType.Future: case SecurityType.FutureOption: return new InteractiveBrokersFeeModel(); case SecurityType.Commodity: default: return new ConstantFeeModel(0m); } } /// <summary> /// Gets a new slippage model that represents this brokerage's fill slippage behavior /// </summary> /// <param name="security">The security to get a slippage model for</param> /// <returns>The new slippage model for this brokerage</returns> public virtual ISlippageModel GetSlippageModel(Security security) { switch (security.Type) { case SecurityType.Base: case SecurityType.Equity: case SecurityType.Index: return new ConstantSlippageModel(0); case SecurityType.Forex: case SecurityType.Cfd: case SecurityType.Crypto: return new ConstantSlippageModel(0); case SecurityType.Commodity: case SecurityType.Option: case SecurityType.FutureOption: case SecurityType.Future: default: return new ConstantSlippageModel(0); } } /// <summary> /// Gets a new settlement model for the security /// </summary> /// <param name="security">The security to get a settlement model for</param> /// <returns>The settlement model for this brokerage</returns> public virtual ISettlementModel GetSettlementModel(Security security) { if (AccountType == AccountType.Cash) { switch (security.Type) { case SecurityType.Equity: return new DelayedSettlementModel(Equity.DefaultSettlementDays, Equity.DefaultSettlementTime); case SecurityType.Option: return new DelayedSettlementModel(Option.DefaultSettlementDays, Option.DefaultSettlementTime); } } return new ImmediateSettlementModel(); } /// <summary> /// Gets a new settlement model for the security /// </summary> /// <param name="security">The security to get a settlement model for</param> /// <param name="accountType">The account type</param> /// <returns>The settlement model for this brokerage</returns> [Obsolete("Flagged deprecated and will remove December 1st 2018")] public ISettlementModel GetSettlementModel(Security security, AccountType accountType) { return GetSettlementModel(security); } /// <summary> /// Gets a new buying power model for the security, returning the default model with the security's configured leverage. /// For cash accounts, leverage = 1 is used. /// </summary> /// <param name="security">The security to get a buying power model for</param> /// <returns>The buying power model for this brokerage/security</returns> public virtual IBuyingPowerModel GetBuyingPowerModel(Security security) { var leverage = GetLeverage(security); IBuyingPowerModel model; switch (security.Type) { case SecurityType.Crypto: model = new CashBuyingPowerModel(); break; case SecurityType.Forex: case SecurityType.Cfd: model = new SecurityMarginModel(leverage, RequiredFreeBuyingPowerPercent); break; case SecurityType.Option: model = new OptionMarginModel(RequiredFreeBuyingPowerPercent); break; case SecurityType.FutureOption: model = new FuturesOptionsMarginModel(RequiredFreeBuyingPowerPercent, (Option)security); break; case SecurityType.Future: model = new FutureMarginModel(RequiredFreeBuyingPowerPercent, security); break; case SecurityType.Index: default: model = new SecurityMarginModel(leverage, RequiredFreeBuyingPowerPercent); break; } return model; } /// <summary> /// Gets the shortable provider /// </summary> /// <returns>Shortable provider</returns> public virtual IShortableProvider GetShortableProvider() { return ShortableProvider; } /// <summary> /// Gets a new buying power model for the security /// </summary> /// <param name="security">The security to get a buying power model for</param> /// <param name="accountType">The account type</param> /// <returns>The buying power model for this brokerage/security</returns> [Obsolete("Flagged deprecated and will remove December 1st 2018")] public IBuyingPowerModel GetBuyingPowerModel(Security security, AccountType accountType) { return GetBuyingPowerModel(security); } } }
// 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 ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for VirtualNetworkGatewaysOperations. /// </summary> public static partial class VirtualNetworkGatewaysOperationsExtensions { /// <summary> /// Creates or updates a virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update virtual network gateway operation. /// </param> public static VirtualNetworkGateway CreateOrUpdate(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, virtualNetworkGatewayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update virtual network gateway operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> CreateOrUpdateAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the specified virtual network gateway by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static VirtualNetworkGateway Get(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { return operations.GetAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified virtual network gateway by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> GetAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified virtual network gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static void Delete(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { operations.DeleteAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets all virtual network gateways by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<VirtualNetworkGateway> List(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual network gateways by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkGateway>> ListAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Resets the primary of the virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='gatewayVip'> /// Virtual network gateway vip address supplied to the begin reset of the /// active-active feature enabled gateway. /// </param> public static VirtualNetworkGateway Reset(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string)) { return operations.ResetAsync(resourceGroupName, virtualNetworkGatewayName, gatewayVip).GetAwaiter().GetResult(); } /// <summary> /// Resets the primary of the virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='gatewayVip'> /// Virtual network gateway vip address supplied to the begin reset of the /// active-active feature enabled gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> ResetAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ResetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, gatewayVip, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Generates VPN client package for P2S client of the virtual network gateway /// in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN client /// package operation. /// </param> public static string Generatevpnclientpackage(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters) { return operations.GeneratevpnclientpackageAsync(resourceGroupName, virtualNetworkGatewayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Generates VPN client package for P2S client of the virtual network gateway /// in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the generate virtual network gateway VPN client /// package operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> GeneratevpnclientpackageAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GeneratevpnclientpackageWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The GetBgpPeerStatus operation retrieves the status of all BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer to retrieve the status of. /// </param> public static BgpPeerStatusListResult GetBgpPeerStatus(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string)) { return operations.GetBgpPeerStatusAsync(resourceGroupName, virtualNetworkGatewayName, peer).GetAwaiter().GetResult(); } /// <summary> /// The GetBgpPeerStatus operation retrieves the status of all BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer to retrieve the status of. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BgpPeerStatusListResult> GetBgpPeerStatusAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetBgpPeerStatusWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, peer, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// This operation retrieves a list of routes the virtual network gateway has /// learned, including routes learned from BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static GatewayRouteListResult GetLearnedRoutes(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { return operations.GetLearnedRoutesAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// This operation retrieves a list of routes the virtual network gateway has /// learned, including routes learned from BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GatewayRouteListResult> GetLearnedRoutesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetLearnedRoutesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// This operation retrieves a list of routes the virtual network gateway is /// advertising to the specified peer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer /// </param> public static GatewayRouteListResult GetAdvertisedRoutes(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer) { return operations.GetAdvertisedRoutesAsync(resourceGroupName, virtualNetworkGatewayName, peer).GetAwaiter().GetResult(); } /// <summary> /// This operation retrieves a list of routes the virtual network gateway is /// advertising to the specified peer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GatewayRouteListResult> GetAdvertisedRoutesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetAdvertisedRoutesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, peer, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update virtual network gateway operation. /// </param> public static VirtualNetworkGateway BeginCreateOrUpdate(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkGatewayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update virtual network gateway operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> BeginCreateOrUpdateAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified virtual network gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static void BeginDelete(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { operations.BeginDeleteAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified virtual network gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Resets the primary of the virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='gatewayVip'> /// Virtual network gateway vip address supplied to the begin reset of the /// active-active feature enabled gateway. /// </param> public static VirtualNetworkGateway BeginReset(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string)) { return operations.BeginResetAsync(resourceGroupName, virtualNetworkGatewayName, gatewayVip).GetAwaiter().GetResult(); } /// <summary> /// Resets the primary of the virtual network gateway in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='gatewayVip'> /// Virtual network gateway vip address supplied to the begin reset of the /// active-active feature enabled gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<VirtualNetworkGateway> BeginResetAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginResetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, gatewayVip, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The GetBgpPeerStatus operation retrieves the status of all BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer to retrieve the status of. /// </param> public static BgpPeerStatusListResult BeginGetBgpPeerStatus(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string)) { return operations.BeginGetBgpPeerStatusAsync(resourceGroupName, virtualNetworkGatewayName, peer).GetAwaiter().GetResult(); } /// <summary> /// The GetBgpPeerStatus operation retrieves the status of all BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer to retrieve the status of. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BgpPeerStatusListResult> BeginGetBgpPeerStatusAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginGetBgpPeerStatusWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, peer, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// This operation retrieves a list of routes the virtual network gateway has /// learned, including routes learned from BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> public static GatewayRouteListResult BeginGetLearnedRoutes(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName) { return operations.BeginGetLearnedRoutesAsync(resourceGroupName, virtualNetworkGatewayName).GetAwaiter().GetResult(); } /// <summary> /// This operation retrieves a list of routes the virtual network gateway has /// learned, including routes learned from BGP peers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GatewayRouteListResult> BeginGetLearnedRoutesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginGetLearnedRoutesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// This operation retrieves a list of routes the virtual network gateway is /// advertising to the specified peer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer /// </param> public static GatewayRouteListResult BeginGetAdvertisedRoutes(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer) { return operations.BeginGetAdvertisedRoutesAsync(resourceGroupName, virtualNetworkGatewayName, peer).GetAwaiter().GetResult(); } /// <summary> /// This operation retrieves a list of routes the virtual network gateway is /// advertising to the specified peer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='peer'> /// The IP address of the peer /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GatewayRouteListResult> BeginGetAdvertisedRoutesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginGetAdvertisedRoutesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, peer, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all virtual network gateways by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<VirtualNetworkGateway> ListNext(this IVirtualNetworkGatewaysOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all virtual network gateways by resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<VirtualNetworkGateway>> ListNextAsync(this IVirtualNetworkGatewaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Linq; using NBitcoin.Altcoins.HashX11; using NBitcoin.Crypto; using NBitcoin.DataEncoders; using NBitcoin.Protocol; namespace NBitcoin.Altcoins { // Reference: https://github.com/dogecash/dogecash/blob/master/src/chainparams.cpp public class DogeCash : NetworkSetBase { public static DogeCash Instance { get; } = new DogeCash(); public override string CryptoCode => "DOGEC"; private DogeCash() { } public class DogeCashConsensusFactory : ConsensusFactory { private DogeCashConsensusFactory() { } public static DogeCashConsensusFactory Instance { get; } = new DogeCashConsensusFactory(); public override BlockHeader CreateBlockHeader() { return new DogeCashBlockHeader(); } public override Block CreateBlock() { return new DogeCashBlock(new DogeCashBlockHeader()); } } #pragma warning disable CS0618 // Type or member is obsolete public class DogeCashBlockHeader : BlockHeader { // https://github.com/dogecash/dogecas/blob/master/src/primitives/block.cpp#L19 private static byte[] CalculateHash(byte[] data, int offset, int count) { var h = new Quark().ComputeBytes(data.Skip(offset).Take(count).ToArray()); return h; } protected override HashStreamBase CreateHashStream() { return BufferedHashStream.CreateFrom(CalculateHash); } } public class DogeCashBlock : Block { public DogeCashBlock(DogeCashBlockHeader h) : base(h) { } public override ConsensusFactory GetConsensusFactory() { return Instance.Mainnet.Consensus.ConsensusFactory; } } #pragma warning restore CS0618 // Type or member is obsolete protected override void PostInit() { RegisterDefaultCookiePath("DOGEC"); } protected override NetworkBuilder CreateMainnet() { var builder = new NetworkBuilder(); builder.SetConsensus(new Consensus { SubsidyHalvingInterval = 210000, MajorityEnforceBlockUpgrade = 8100, MajorityRejectBlockOutdated = 10260, MajorityWindow = 10800, BIP34Hash = new uint256("000000cb303fa18385fca0610ce525db98f32a5f55f5cd9bf5ff83d88b537915"), PowLimit = new Target(0 >> 1), MinimumChainWork = new uint256("000000000000000000000000000000000000000000000000c2ba8ca4fb1f06cb"), PowTargetTimespan = TimeSpan.FromSeconds(24 * 60 * 60), PowTargetSpacing = TimeSpan.FromSeconds(1 * 60), PowAllowMinDifficultyBlocks = true, CoinbaseMaturity = 30, PowNoRetargeting = false, RuleChangeActivationThreshold = 1916, MinerConfirmationWindow = 2016, ConsensusFactory = DogeCashConsensusFactory.Instance, SupportSegwit = false, CoinType = 385 }) .SetBase58Bytes(Base58Type.PUBKEY_ADDRESS, new byte[] { 31 }) .SetBase58Bytes(Base58Type.SCRIPT_ADDRESS, new byte[] { 19 }) .SetBase58Bytes(Base58Type.SECRET_KEY, new byte[] { 122 }) .SetBase58Bytes(Base58Type.EXT_PUBLIC_KEY, new byte[] {0x02, 0x2D, 0x25, 0x33}) .SetBase58Bytes(Base58Type.EXT_SECRET_KEY, new byte[] {0x02, 0x21, 0x31, 0x2B}) .SetBech32(Bech32Type.WITNESS_PUBKEY_ADDRESS, Encoders.Bech32("DogeCash")) .SetBech32(Bech32Type.WITNESS_SCRIPT_ADDRESS, Encoders.Bech32("DogeCash")) .SetMagic(0x191643a0) .SetPort(56740) .SetRPCPort(51573) .SetMaxP2PVersion(70920) .SetName("DogeCash-main") .AddAlias("DogeCash-mainnet") .AddDNSSeeds(new[] { new DNSSeedData("dogec1", "seeds.dogec.io"), new DNSSeedData("dogec2", "x9.seeds.dogec.io"), new DNSSeedData("dogec3", "testseeds.dogec.io") }) .AddSeeds(new NetworkAddress[0]) .SetGenesis("01000000000000000000000000000000000000000000000000000000000000000000000014e427b75837280517873799a954e87b8b0484f3f1df927888a0ff4fd3a0c9f7bb2eac56f0ff0f1edfa624000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff8604ffff001d01044c7d323031372d30392d32312032323a30313a3034203a20426974636f696e20426c6f636b204861736820666f722048656967687420343836333832203a2030303030303030303030303030303030303039326431356535623365366538323639333938613834613630616535613264626434653766343331313939643033ffffffff0100ba1dd205000000434104c10e83b2703ccf322f7dbd62dd5855ac7c10bd055814ce121ba32607d573b8810c02c0582aed05b4deb9c4b77b26d92428c61256cd42774babea0a073b2ed0c9ac00000000"); return builder; } protected override NetworkBuilder CreateTestnet() { var builder = new NetworkBuilder(); builder.SetConsensus(new Consensus { SubsidyHalvingInterval = 210000, MajorityEnforceBlockUpgrade = 51, MajorityRejectBlockOutdated = 75, MajorityWindow = 100, BIP34Hash = new uint256("0000000000000000000000000000000000000000000000000000000000000000"), PowLimit = new Target(0 >> 1), MinimumChainWork = new uint256("0000000000000000000000000000000000000000000000000000000000100010"), PowTargetTimespan = TimeSpan.FromSeconds(24 * 60 * 60), PowTargetSpacing = TimeSpan.FromSeconds(1 * 60), PowAllowMinDifficultyBlocks = true, CoinbaseMaturity = 30, PowNoRetargeting = false, RuleChangeActivationThreshold = 1512, MinerConfirmationWindow = 2016, ConsensusFactory = DogeCashConsensusFactory.Instance, SupportSegwit = false, CoinType = 1 }) .SetBase58Bytes(Base58Type.PUBKEY_ADDRESS, new byte[] { 31 }) .SetBase58Bytes(Base58Type.SCRIPT_ADDRESS, new byte[] { 19 }) .SetBase58Bytes(Base58Type.SECRET_KEY, new byte[] { 122 }) .SetBase58Bytes(Base58Type.EXT_PUBLIC_KEY, new byte[] {0x02, 0x2D, 0x25, 0x33}) .SetBase58Bytes(Base58Type.EXT_SECRET_KEY, new byte[] {0x02, 0x21, 0x31, 0x2B}) .SetBech32(Bech32Type.WITNESS_PUBKEY_ADDRESS, Encoders.Bech32("tDogeCash")) .SetBech32(Bech32Type.WITNESS_SCRIPT_ADDRESS, Encoders.Bech32("tDogeCash")) .SetMagic(0x191643a0) .SetPort(56740) .SetRPCPort(51375) .SetMaxP2PVersion(70920) .SetName("DogeCash-test") .AddAlias("DogeCash-testnet") .AddSeeds(new NetworkAddress[0]) //testnet down for now .SetGenesis("0100000000000000000000000000000000000000000000000000000000000000000000008c5b00d67050180b3a90addb9cd1aabbb3dd79ce20fc071d428ce374581b3f7cde30df5cf0ff0f1e1a1754000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff3b04ffff001d010433446f676543617368205265706f7765726564204c61756e6368202d20616b736861796e65787573202d204c6971756964333639ffffffff0100000000000000004341047a7df379bd5e6b93b164968c10fcbb141ecb3c6dc1a5e181c2a62328405cf82311dd5b40bf45430320a4f30add05c8e3e16dd56c52d65f7abe475189564bf2b1ac00000000"); return builder; } protected override NetworkBuilder CreateRegtest() { var builder = new NetworkBuilder(); var res = builder.SetConsensus(new Consensus { SubsidyHalvingInterval = 150, MajorityEnforceBlockUpgrade = 750, MajorityRejectBlockOutdated = 950, MajorityWindow = 1000, BIP34Hash = new uint256(), PowLimit = new Target(0 >> 1), MinimumChainWork = new uint256("0x000000000000000000000000000000000000000000000100a308553b4863b755"), PowTargetTimespan = TimeSpan.FromSeconds(1 * 60 * 40), PowTargetSpacing = TimeSpan.FromSeconds(1 * 60), PowAllowMinDifficultyBlocks = false, CoinbaseMaturity = 10, PowNoRetargeting = true, RuleChangeActivationThreshold = 1916, MinerConfirmationWindow = 2016, ConsensusFactory = DogeCashConsensusFactory.Instance, SupportSegwit = false }) .SetBase58Bytes(Base58Type.PUBKEY_ADDRESS, new byte[] { 31 }) .SetBase58Bytes(Base58Type.SCRIPT_ADDRESS, new byte[] { 19 }) .SetBase58Bytes(Base58Type.SECRET_KEY, new byte[] { 122 }) .SetBase58Bytes(Base58Type.EXT_PUBLIC_KEY, new byte[] {0x02, 0x2D, 0x25, 0x33}) .SetBase58Bytes(Base58Type.EXT_SECRET_KEY, new byte[] {0x02, 0x21, 0x31, 0x2B}) .SetBech32(Bech32Type.WITNESS_PUBKEY_ADDRESS, Encoders.Bech32("tDogeCash")) .SetBech32(Bech32Type.WITNESS_SCRIPT_ADDRESS, Encoders.Bech32("tDogeCash")) .SetMagic(0x191643a0) .SetPort(56740) .SetRPCPort(51478) .SetMaxP2PVersion(70920) .SetName("DogeCash-reg") .AddAlias("DogeCash-regtest") .AddDNSSeeds(new DNSSeedData[0]) .AddSeeds(new NetworkAddress[0]) //No regtest at the moment .SetGenesis("01000000000000000000000000000000000000000000000000000000000000000000000014e427b75837280517873799a954e87b8b0484f3f1df927888a0ff4fd3a0c9f7bb2eac56ffff7f20393000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff8604ffff001d01044c7d323031372d30392d32312032323a30313a3034203a20426974636f696e20426c6f636b204861736820666f722048656967687420343836333832203a2030303030303030303030303030303030303039326431356535623365366538323639333938613834613630616535613264626434653766343331313939643033ffffffff0100ba1dd205000000434104c10e83b2703ccf322f7dbd62dd5855ac7c10bd055814ce121ba32607d573b8810c02c0582aed05b4deb9c4b77b26d92428c61256cd42774babea0a073b2ed0c9ac00000000"); return builder; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dataproc.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAutoscalingPolicyServiceClientTest { [xunit::FactAttribute] public void CreateAutoscalingPolicyRequestObject() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); CreateAutoscalingPolicyRequest request = new CreateAutoscalingPolicyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Policy = new AutoscalingPolicy(), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateAutoscalingPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy response = client.CreateAutoscalingPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateAutoscalingPolicyRequestObjectAsync() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); CreateAutoscalingPolicyRequest request = new CreateAutoscalingPolicyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Policy = new AutoscalingPolicy(), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateAutoscalingPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AutoscalingPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy responseCallSettings = await client.CreateAutoscalingPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AutoscalingPolicy responseCancellationToken = await client.CreateAutoscalingPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateAutoscalingPolicy() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); CreateAutoscalingPolicyRequest request = new CreateAutoscalingPolicyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Policy = new AutoscalingPolicy(), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateAutoscalingPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy response = client.CreateAutoscalingPolicy(request.Parent, request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateAutoscalingPolicyAsync() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); CreateAutoscalingPolicyRequest request = new CreateAutoscalingPolicyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Policy = new AutoscalingPolicy(), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateAutoscalingPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AutoscalingPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy responseCallSettings = await client.CreateAutoscalingPolicyAsync(request.Parent, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AutoscalingPolicy responseCancellationToken = await client.CreateAutoscalingPolicyAsync(request.Parent, request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateAutoscalingPolicyResourceNames1() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); CreateAutoscalingPolicyRequest request = new CreateAutoscalingPolicyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Policy = new AutoscalingPolicy(), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateAutoscalingPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy response = client.CreateAutoscalingPolicy(request.ParentAsLocationName, request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateAutoscalingPolicyResourceNames1Async() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); CreateAutoscalingPolicyRequest request = new CreateAutoscalingPolicyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Policy = new AutoscalingPolicy(), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateAutoscalingPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AutoscalingPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy responseCallSettings = await client.CreateAutoscalingPolicyAsync(request.ParentAsLocationName, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AutoscalingPolicy responseCancellationToken = await client.CreateAutoscalingPolicyAsync(request.ParentAsLocationName, request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateAutoscalingPolicyResourceNames2() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); CreateAutoscalingPolicyRequest request = new CreateAutoscalingPolicyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Policy = new AutoscalingPolicy(), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateAutoscalingPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy response = client.CreateAutoscalingPolicy(request.ParentAsRegionName, request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateAutoscalingPolicyResourceNames2Async() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); CreateAutoscalingPolicyRequest request = new CreateAutoscalingPolicyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Policy = new AutoscalingPolicy(), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.CreateAutoscalingPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AutoscalingPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy responseCallSettings = await client.CreateAutoscalingPolicyAsync(request.ParentAsRegionName, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AutoscalingPolicy responseCancellationToken = await client.CreateAutoscalingPolicyAsync(request.ParentAsRegionName, request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateAutoscalingPolicyRequestObject() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); UpdateAutoscalingPolicyRequest request = new UpdateAutoscalingPolicyRequest { Policy = new AutoscalingPolicy(), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.UpdateAutoscalingPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy response = client.UpdateAutoscalingPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateAutoscalingPolicyRequestObjectAsync() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); UpdateAutoscalingPolicyRequest request = new UpdateAutoscalingPolicyRequest { Policy = new AutoscalingPolicy(), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.UpdateAutoscalingPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AutoscalingPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy responseCallSettings = await client.UpdateAutoscalingPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AutoscalingPolicy responseCancellationToken = await client.UpdateAutoscalingPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateAutoscalingPolicy() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); UpdateAutoscalingPolicyRequest request = new UpdateAutoscalingPolicyRequest { Policy = new AutoscalingPolicy(), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.UpdateAutoscalingPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy response = client.UpdateAutoscalingPolicy(request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateAutoscalingPolicyAsync() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); UpdateAutoscalingPolicyRequest request = new UpdateAutoscalingPolicyRequest { Policy = new AutoscalingPolicy(), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.UpdateAutoscalingPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AutoscalingPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy responseCallSettings = await client.UpdateAutoscalingPolicyAsync(request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AutoscalingPolicy responseCancellationToken = await client.UpdateAutoscalingPolicyAsync(request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAutoscalingPolicyRequestObject() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); GetAutoscalingPolicyRequest request = new GetAutoscalingPolicyRequest { AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAutoscalingPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy response = client.GetAutoscalingPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAutoscalingPolicyRequestObjectAsync() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); GetAutoscalingPolicyRequest request = new GetAutoscalingPolicyRequest { AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAutoscalingPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AutoscalingPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy responseCallSettings = await client.GetAutoscalingPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AutoscalingPolicy responseCancellationToken = await client.GetAutoscalingPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAutoscalingPolicy() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); GetAutoscalingPolicyRequest request = new GetAutoscalingPolicyRequest { AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAutoscalingPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy response = client.GetAutoscalingPolicy(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAutoscalingPolicyAsync() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); GetAutoscalingPolicyRequest request = new GetAutoscalingPolicyRequest { AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAutoscalingPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AutoscalingPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy responseCallSettings = await client.GetAutoscalingPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AutoscalingPolicy responseCancellationToken = await client.GetAutoscalingPolicyAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAutoscalingPolicyResourceNames() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); GetAutoscalingPolicyRequest request = new GetAutoscalingPolicyRequest { AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAutoscalingPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy response = client.GetAutoscalingPolicy(request.AutoscalingPolicyName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAutoscalingPolicyResourceNamesAsync() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); GetAutoscalingPolicyRequest request = new GetAutoscalingPolicyRequest { AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), }; AutoscalingPolicy expectedResponse = new AutoscalingPolicy { Id = "id74b70bb8", AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), BasicAlgorithm = new BasicAutoscalingAlgorithm(), WorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), SecondaryWorkerConfig = new InstanceGroupAutoscalingPolicyConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAutoscalingPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AutoscalingPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); AutoscalingPolicy responseCallSettings = await client.GetAutoscalingPolicyAsync(request.AutoscalingPolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AutoscalingPolicy responseCancellationToken = await client.GetAutoscalingPolicyAsync(request.AutoscalingPolicyName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAutoscalingPolicyRequestObject() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); DeleteAutoscalingPolicyRequest request = new DeleteAutoscalingPolicyRequest { AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAutoscalingPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); client.DeleteAutoscalingPolicy(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAutoscalingPolicyRequestObjectAsync() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); DeleteAutoscalingPolicyRequest request = new DeleteAutoscalingPolicyRequest { AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAutoscalingPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteAutoscalingPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAutoscalingPolicyAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAutoscalingPolicy() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); DeleteAutoscalingPolicyRequest request = new DeleteAutoscalingPolicyRequest { AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAutoscalingPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); client.DeleteAutoscalingPolicy(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAutoscalingPolicyAsync() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); DeleteAutoscalingPolicyRequest request = new DeleteAutoscalingPolicyRequest { AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAutoscalingPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteAutoscalingPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAutoscalingPolicyAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAutoscalingPolicyResourceNames() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); DeleteAutoscalingPolicyRequest request = new DeleteAutoscalingPolicyRequest { AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAutoscalingPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); client.DeleteAutoscalingPolicy(request.AutoscalingPolicyName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAutoscalingPolicyResourceNamesAsync() { moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient> mockGrpcClient = new moq::Mock<AutoscalingPolicyService.AutoscalingPolicyServiceClient>(moq::MockBehavior.Strict); DeleteAutoscalingPolicyRequest request = new DeleteAutoscalingPolicyRequest { AutoscalingPolicyName = AutoscalingPolicyName.FromProjectLocationAutoscalingPolicy("[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAutoscalingPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AutoscalingPolicyServiceClient client = new AutoscalingPolicyServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteAutoscalingPolicyAsync(request.AutoscalingPolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAutoscalingPolicyAsync(request.AutoscalingPolicyName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
/* Copyright(c) Microsoft Open Technologies, Inc. All rights reserved. The MIT License(MIT) 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 Shield.Communication; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Text; namespace Shield { public enum ConnectionState { NotConnected = 0, Connecting = 1, Connected = 2, CouldNotConnect = 3, Disconnecting = 4 } public class AppSettings : INotifyPropertyChanged { private Windows.Storage.ApplicationDataContainer localSettings; private Connections connectionList; public event PropertyChangedEventHandler PropertyChanged; private string[] ConnectionStateText; protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public static AppSettings Instance; private bool isLogging; private StringBuilder log = new StringBuilder(); private bool isListening = false; public AppSettings() { if (Instance == null) { Instance = this; } var loader = new Windows.ApplicationModel.Resources.ResourceLoader(); ConnectionStateText = new[] { loader.GetString("NotConnected"), loader.GetString("Connecting"), loader.GetString("Connected"), loader.GetString("CouldNotConnect"), loader.GetString("Disconnecting") }; DeviceNames = new List<string> { loader.GetString("Bluetooth"), loader.GetString("NetworkDiscovery"), loader.GetString("NetworkDirect") }; try { localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; connectionList = new Connections(); } catch (Exception e) { Debug.WriteLine("Exception while using LocalSettings: " + e.ToString()); throw; } } public bool AddOrUpdateValue(Object value, [CallerMemberName] string Key = null) { bool valueChanged = false; if (localSettings.Values.ContainsKey(Key)) { if (localSettings.Values[Key] != value) { localSettings.Values[Key] = value; valueChanged = true; } } else { localSettings.Values.Add(Key, value); valueChanged = true; } return valueChanged; } public T GetValueOrDefault<T>(T defaultValue, [CallerMemberName] string Key = null) { T value; // If the key exists, retrieve the value. if (localSettings.Values.ContainsKey(Key)) { value = (T) localSettings.Values[Key]; } else { value = defaultValue; } return value; } public bool Remove(Object value, [CallerMemberName] string Key = null) { if (localSettings.Values.ContainsKey(Key)) { localSettings.DeleteContainer(Key); return true; } return false; } public bool AutoConnect { get { return GetValueOrDefault(true); } set { AddOrUpdateValue(value); } } public bool IsListening { get { return isListening; } set { isListening = value; OnPropertyChanged("IsListening"); } } public bool AlwaysRunning { get { return GetValueOrDefault(true); } set { AddOrUpdateValue(value); } } public bool NoListVisible => !ListVisible; public bool ListVisible => ConnectionList != null && ConnectionList.Any(); public int ConnectionIndex { get { return BluetoothVisible ? 0 : NetworkVisible ? 1 : NetworkDirectVisible ? 2 : -1; } set { BluetoothVisible = value == 0; NetworkVisible = value == 1; NetworkDirectVisible = value == 2; } } public bool NotNetworkDirectVisible => !NetworkDirectVisible; public bool BluetoothVisible { get { return GetValueOrDefault(true); } set { AddOrUpdateValue(value); if (value) { NetworkVisible = false; NetworkDirectVisible = false; } OnPropertyChanged("ConnectionIndex"); OnPropertyChanged("NetworkDirectVisible"); OnPropertyChanged("NotNetworkDirectVisible"); MainPage.Instance.SetService(); } } public bool NetworkVisible { get { return GetValueOrDefault(false); } set { AddOrUpdateValue(value); if (value) { BluetoothVisible = false; NetworkDirectVisible = false; } OnPropertyChanged("ConnectionIndex"); OnPropertyChanged("NetworkDirectVisible"); OnPropertyChanged("NotNetworkDirectVisible"); MainPage.Instance.SetService(); } } public bool NetworkDirectVisible { get { return GetValueOrDefault(false); } set { AddOrUpdateValue(value); if (value) { BluetoothVisible = false; NetworkVisible = false; } OnPropertyChanged("ConnectionIndex"); OnPropertyChanged("NotNetworkDirectVisible"); MainPage.Instance.SetService(); } } public string Hostname { get { return GetValueOrDefault(""); } set { AddOrUpdateValue(value); } } public string UserInfo1 { get { return GetValueOrDefault(""); } set { AddOrUpdateValue(value); } } public string UserInfo2 { get { return GetValueOrDefault(""); } set { AddOrUpdateValue(value); } } public string UserInfo3 { get { return GetValueOrDefault(""); } set { AddOrUpdateValue(value); } } public string UserInfo4 { get { return GetValueOrDefault(""); } set { AddOrUpdateValue(value); } } public int Hostport { get { return GetValueOrDefault(0); } set { AddOrUpdateValue(value); } } public string PreviousConnectionName { get { return GetValueOrDefault(""); } set { AddOrUpdateValue(value); } } public string BlobAccountName { get { return GetValueOrDefault(""); } set { AddOrUpdateValue(value); } } public string BlobAccountKey { get { return GetValueOrDefault(""); } set { AddOrUpdateValue(value); } } public Connections ConnectionList { get { return connectionList; } set { connectionList = value; OnPropertyChanged("ConnectionList"); OnPropertyChanged("ListVisible"); OnPropertyChanged("NoListVisible"); } } public bool IsFullscreen { get { return GetValueOrDefault(true); } set { AddOrUpdateValue(value); OnPropertyChanged("IsFullscreen"); OnPropertyChanged("IsControlscreen"); } } public bool IsControlscreen { get { return !IsFullscreen; } set { IsFullscreen = !value; } } public bool IsLogging { get { return isLogging; } set { isLogging = value; OnPropertyChanged("IsLoggingSwitchText"); } } public string IsLoggingSwitchText { get { return isLogging ? "Turn OFF" : "Turn ON"; } } public string LogText { get { return log.ToString(); } set { log.Append(value); OnPropertyChanged("LogText"); } } public StringBuilder Log { get { return log; } } public int CurrentConnectionState { get { return GetValueOrDefault((int) ConnectionState.NotConnected); } set { AddOrUpdateValue(value); OnPropertyChanged("CurrentConnectionStateText"); } } public string CurrentConnectionStateText { get { return this.ConnectionStateText[CurrentConnectionState]; } } public List<string> DeviceNames { get; set; } public void ReportChanged(string key) { OnPropertyChanged(key); } public bool MissingBackButton => !Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"); } }
using System; using System.Windows.Forms; using System.Drawing; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { public delegate string GetPersistStringCallback(); public class DockContentHandler : IDisposable, IDockDragSource { public DockContentHandler(Form form) : this(form, null) { } public DockContentHandler(Form form, GetPersistStringCallback getPersistStringCallback) { if (!(form is IDockContent)) throw new ArgumentException(Strings.DockContent_Constructor_InvalidForm, "form"); m_form = form; m_getPersistStringCallback = getPersistStringCallback; m_events = new EventHandlerList(); Form.Disposed +=new EventHandler(Form_Disposed); Form.TextChanged += new EventHandler(Form_TextChanged); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { DockPanel = null; if (m_autoHideTab != null) m_autoHideTab.Dispose(); if (m_tab != null) m_tab.Dispose(); Form.Disposed -= new EventHandler(Form_Disposed); Form.TextChanged -= new EventHandler(Form_TextChanged); m_events.Dispose(); } } private Form m_form; public Form Form { get { return m_form; } } public IDockContent Content { get { return Form as IDockContent; } } private IDockContent m_previousActive = null; public IDockContent PreviousActive { get { return m_previousActive; } internal set { m_previousActive = value; } } private IDockContent m_nextActive = null; public IDockContent NextActive { get { return m_nextActive; } internal set { m_nextActive = value; } } private EventHandlerList m_events; private EventHandlerList Events { get { return m_events; } } private bool m_allowEndUserDocking = true; public bool AllowEndUserDocking { get { return m_allowEndUserDocking; } set { m_allowEndUserDocking = value; } } private double m_autoHidePortion = 0.25; public double AutoHidePortion { get { return m_autoHidePortion; } set { if (value <= 0) throw(new ArgumentOutOfRangeException(Strings.DockContentHandler_AutoHidePortion_OutOfRange)); if (m_autoHidePortion == value) return; m_autoHidePortion = value; if (DockPanel == null) return; if (DockPanel.ActiveAutoHideContent == Content) DockPanel.PerformLayout(); } } private bool m_closeButton = true; public bool CloseButton { get { return m_closeButton; } set { if (m_closeButton == value) return; m_closeButton = value; if (IsActiveContentHandler) Pane.RefreshChanges(); } } private bool m_closeButtonVisible = true; /// <summary> /// Determines whether the close button is visible on the content /// </summary> public bool CloseButtonVisible { get { return m_closeButtonVisible; } set { if (m_closeButtonVisible == value) return; m_closeButtonVisible = value; if (IsActiveContentHandler) Pane.RefreshChanges(); } } private bool IsActiveContentHandler { get { return Pane != null && Pane.ActiveContent != null && Pane.ActiveContent.DockHandler == this; } } private DockState DefaultDockState { get { if (ShowHint != DockState.Unknown && ShowHint != DockState.Hidden) return ShowHint; if ((DockAreas & DockAreas.Document) != 0) return DockState.Document; if ((DockAreas & DockAreas.DockRight) != 0) return DockState.DockRight; if ((DockAreas & DockAreas.DockLeft) != 0) return DockState.DockLeft; if ((DockAreas & DockAreas.DockBottom) != 0) return DockState.DockBottom; if ((DockAreas & DockAreas.DockTop) != 0) return DockState.DockTop; return DockState.Unknown; } } private DockState DefaultShowState { get { if (ShowHint != DockState.Unknown) return ShowHint; if ((DockAreas & DockAreas.Document) != 0) return DockState.Document; if ((DockAreas & DockAreas.DockRight) != 0) return DockState.DockRight; if ((DockAreas & DockAreas.DockLeft) != 0) return DockState.DockLeft; if ((DockAreas & DockAreas.DockBottom) != 0) return DockState.DockBottom; if ((DockAreas & DockAreas.DockTop) != 0) return DockState.DockTop; if ((DockAreas & DockAreas.Float) != 0) return DockState.Float; return DockState.Unknown; } } private DockAreas m_allowedAreas = DockAreas.DockLeft | DockAreas.DockRight | DockAreas.DockTop | DockAreas.DockBottom | DockAreas.Document | DockAreas.Float; public DockAreas DockAreas { get { return m_allowedAreas; } set { if (m_allowedAreas == value) return; if (!DockHelper.IsDockStateValid(DockState, value)) throw(new InvalidOperationException(Strings.DockContentHandler_DockAreas_InvalidValue)); m_allowedAreas = value; if (!DockHelper.IsDockStateValid(ShowHint, m_allowedAreas)) ShowHint = DockState.Unknown; } } private DockState m_dockState = DockState.Unknown; public DockState DockState { get { return m_dockState; } set { if (m_dockState == value) return; DockPanel.SuspendLayout(true); if (value == DockState.Hidden) IsHidden = true; else SetDockState(false, value, Pane); DockPanel.ResumeLayout(true, true); } } private DockPanel m_dockPanel = null; public DockPanel DockPanel { get { return m_dockPanel; } set { if (m_dockPanel == value) return; Pane = null; if (m_dockPanel != null) m_dockPanel.RemoveContent(Content); if (m_tab != null) { m_tab.Dispose(); m_tab = null; } if (m_autoHideTab != null) { m_autoHideTab.Dispose(); m_autoHideTab = null; } m_dockPanel = value; if (m_dockPanel != null) { m_dockPanel.AddContent(Content); Form.TopLevel = false; Form.FormBorderStyle = FormBorderStyle.None; Form.ShowInTaskbar = false; Form.WindowState = FormWindowState.Normal; if (Win32Helper.IsRunningOnMono) return; NativeMethods.SetWindowPos(Form.Handle, IntPtr.Zero, 0, 0, 0, 0, Win32.FlagsSetWindowPos.SWP_NOACTIVATE | Win32.FlagsSetWindowPos.SWP_NOMOVE | Win32.FlagsSetWindowPos.SWP_NOSIZE | Win32.FlagsSetWindowPos.SWP_NOZORDER | Win32.FlagsSetWindowPos.SWP_NOOWNERZORDER | Win32.FlagsSetWindowPos.SWP_FRAMECHANGED); } } } public Icon Icon { get { return Form.Icon; } } public DockPane Pane { get { return IsFloat ? FloatPane : PanelPane; } set { if (Pane == value) return; DockPanel.SuspendLayout(true); DockPane oldPane = Pane; SuspendSetDockState(); FloatPane = (value == null ? null : (value.IsFloat ? value : FloatPane)); PanelPane = (value == null ? null : (value.IsFloat ? PanelPane : value)); ResumeSetDockState(IsHidden, value != null ? value.DockState : DockState.Unknown, oldPane); DockPanel.ResumeLayout(true, true); } } private bool m_isHidden = true; public bool IsHidden { get { return m_isHidden; } set { if (m_isHidden == value) return; SetDockState(value, VisibleState, Pane); } } private string m_tabText = null; public string TabText { get { return m_tabText == null || m_tabText == "" ? Form.Text : m_tabText; } set { if (m_tabText == value) return; m_tabText = value; if (Pane != null) Pane.RefreshChanges(); } } private DockState m_visibleState = DockState.Unknown; public DockState VisibleState { get { return m_visibleState; } set { if (m_visibleState == value) return; SetDockState(IsHidden, value, Pane); } } private bool m_isFloat = false; public bool IsFloat { get { return m_isFloat; } set { if (m_isFloat == value) return; DockState visibleState = CheckDockState(value); if (visibleState == DockState.Unknown) throw new InvalidOperationException(Strings.DockContentHandler_IsFloat_InvalidValue); SetDockState(IsHidden, visibleState, Pane); } } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public DockState CheckDockState(bool isFloat) { DockState dockState; if (isFloat) { if (!IsDockStateValid(DockState.Float)) dockState = DockState.Unknown; else dockState = DockState.Float; } else { dockState = (PanelPane != null) ? PanelPane.DockState : DefaultDockState; if (dockState != DockState.Unknown && !IsDockStateValid(dockState)) dockState = DockState.Unknown; } return dockState; } private DockPane m_panelPane = null; public DockPane PanelPane { get { return m_panelPane; } set { if (m_panelPane == value) return; if (value != null) { if (value.IsFloat || value.DockPanel != DockPanel) throw new InvalidOperationException(Strings.DockContentHandler_DockPane_InvalidValue); } DockPane oldPane = Pane; if (m_panelPane != null) RemoveFromPane(m_panelPane); m_panelPane = value; if (m_panelPane != null) { m_panelPane.AddContent(Content); SetDockState(IsHidden, IsFloat ? DockState.Float : m_panelPane.DockState, oldPane); } else SetDockState(IsHidden, DockState.Unknown, oldPane); } } private void RemoveFromPane(DockPane pane) { pane.RemoveContent(Content); SetPane(null); if (pane.Contents.Count == 0) pane.Dispose(); } private DockPane m_floatPane = null; public DockPane FloatPane { get { return m_floatPane; } set { if (m_floatPane == value) return; if (value != null) { if (!value.IsFloat || value.DockPanel != DockPanel) throw new InvalidOperationException(Strings.DockContentHandler_FloatPane_InvalidValue); } DockPane oldPane = Pane; if (m_floatPane != null) RemoveFromPane(m_floatPane); m_floatPane = value; if (m_floatPane != null) { m_floatPane.AddContent(Content); SetDockState(IsHidden, IsFloat ? DockState.Float : VisibleState, oldPane); } else SetDockState(IsHidden, DockState.Unknown, oldPane); } } private int m_countSetDockState = 0; private void SuspendSetDockState() { m_countSetDockState ++; } private void ResumeSetDockState() { m_countSetDockState --; if (m_countSetDockState < 0) m_countSetDockState = 0; } internal bool IsSuspendSetDockState { get { return m_countSetDockState != 0; } } private void ResumeSetDockState(bool isHidden, DockState visibleState, DockPane oldPane) { ResumeSetDockState(); SetDockState(isHidden, visibleState, oldPane); } internal void SetDockState(bool isHidden, DockState visibleState, DockPane oldPane) { if (IsSuspendSetDockState) return; if (DockPanel == null && visibleState != DockState.Unknown) throw new InvalidOperationException(Strings.DockContentHandler_SetDockState_NullPanel); if (visibleState == DockState.Hidden || (visibleState != DockState.Unknown && !IsDockStateValid(visibleState))) throw new InvalidOperationException(Strings.DockContentHandler_SetDockState_InvalidState); DockPanel dockPanel = DockPanel; if (dockPanel != null) dockPanel.SuspendLayout(true); SuspendSetDockState(); DockState oldDockState = DockState; if (m_isHidden != isHidden || oldDockState == DockState.Unknown) { m_isHidden = isHidden; } m_visibleState = visibleState; m_dockState = isHidden ? DockState.Hidden : visibleState; if (visibleState == DockState.Unknown) Pane = null; else { m_isFloat = (m_visibleState == DockState.Float); if (Pane == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, visibleState, true); else if (Pane.DockState != visibleState) { if (Pane.Contents.Count == 1) Pane.SetDockState(visibleState); else Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, visibleState, true); } } if (Form.ContainsFocus) { if (DockState == DockState.Hidden || DockState == DockState.Unknown) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.GiveUpFocus(Content); } } } SetPaneAndVisible(Pane); if (oldPane != null && !oldPane.IsDisposed && oldDockState == oldPane.DockState) RefreshDockPane(oldPane); if (Pane != null && DockState == Pane.DockState) { if ((Pane != oldPane) || (Pane == oldPane && oldDockState != oldPane.DockState)) { // Avoid early refresh of hidden AutoHide panes if ((Pane.DockWindow == null || Pane.DockWindow.Visible || Pane.IsHidden) && !Pane.IsAutoHide) { RefreshDockPane(Pane); } } } if (oldDockState != DockState) { if (DockState == DockState.Hidden || DockState == DockState.Unknown || DockHelper.IsDockStateAutoHide(DockState)) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.RemoveFromList(Content); } } else if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.AddToList(Content); } ResetAutoHidePortion(oldDockState, DockState); OnDockStateChanged(EventArgs.Empty); } ResumeSetDockState(); if (dockPanel != null) dockPanel.ResumeLayout(true, true); } private void ResetAutoHidePortion(DockState oldState, DockState newState) { if (oldState == newState || DockHelper.ToggleAutoHideState(oldState) == newState) return; switch (newState) { case DockState.DockTop: case DockState.DockTopAutoHide: AutoHidePortion = DockPanel.DockTopPortion; break; case DockState.DockLeft: case DockState.DockLeftAutoHide: AutoHidePortion = DockPanel.DockLeftPortion; break; case DockState.DockBottom: case DockState.DockBottomAutoHide: AutoHidePortion = DockPanel.DockBottomPortion; break; case DockState.DockRight: case DockState.DockRightAutoHide: AutoHidePortion = DockPanel.DockRightPortion; break; } } private static void RefreshDockPane(DockPane pane) { pane.RefreshChanges(); pane.ValidateActiveContent(); } internal string PersistString { get { return GetPersistStringCallback == null ? Form.GetType().ToString() : GetPersistStringCallback(); } } private GetPersistStringCallback m_getPersistStringCallback = null; public GetPersistStringCallback GetPersistStringCallback { get { return m_getPersistStringCallback; } set { m_getPersistStringCallback = value; } } private bool m_hideOnClose = false; public bool HideOnClose { get { return m_hideOnClose; } set { m_hideOnClose = value; } } private DockState m_showHint = DockState.Unknown; public DockState ShowHint { get { return m_showHint; } set { if (!DockHelper.IsDockStateValid(value, DockAreas)) throw (new InvalidOperationException(Strings.DockContentHandler_ShowHint_InvalidValue)); if (m_showHint == value) return; m_showHint = value; } } private bool m_isActivated = false; public bool IsActivated { get { return m_isActivated; } internal set { if (m_isActivated == value) return; m_isActivated = value; } } public bool IsDockStateValid(DockState dockState) { if (DockPanel != null && dockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.SystemMdi) return false; else return DockHelper.IsDockStateValid(dockState, DockAreas); } private ContextMenu m_tabPageContextMenu = null; public ContextMenu TabPageContextMenu { get { return m_tabPageContextMenu; } set { m_tabPageContextMenu = value; } } private string m_toolTipText = null; public string ToolTipText { get { return m_toolTipText; } set { m_toolTipText = value; } } public void Activate() { if (DockPanel == null) Form.Activate(); else if (Pane == null) Show(DockPanel); else { IsHidden = false; Pane.ActiveContent = Content; if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.SystemMdi) { Form.Activate(); return; } else if (DockHelper.IsDockStateAutoHide(DockState)) { if (DockPanel.ActiveAutoHideContent != Content) { DockPanel.ActiveAutoHideContent = null; return; } } if (Form.ContainsFocus) return; if (Win32Helper.IsRunningOnMono) return; DockPanel.ContentFocusManager.Activate(Content); } } public void GiveUpFocus() { if (!Win32Helper.IsRunningOnMono) DockPanel.ContentFocusManager.GiveUpFocus(Content); } private IntPtr m_activeWindowHandle = IntPtr.Zero; internal IntPtr ActiveWindowHandle { get { return m_activeWindowHandle; } set { m_activeWindowHandle = value; } } public void Hide() { IsHidden = true; } internal void SetPaneAndVisible(DockPane pane) { SetPane(pane); SetVisible(); } private void SetPane(DockPane pane) { if (pane != null && pane.DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) { if (Form.Parent is DockPane) SetParent(null); if (Form.MdiParent != DockPanel.ParentForm) { FlagClipWindow = true; Form.MdiParent = DockPanel.ParentForm; } } else { FlagClipWindow = true; if (Form.MdiParent != null) Form.MdiParent = null; if (Form.TopLevel) Form.TopLevel = false; SetParent(pane); } } internal void SetVisible() { bool visible; if (IsHidden) visible = false; else if (Pane != null && Pane.DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) visible = true; else if (Pane != null && Pane.ActiveContent == Content) visible = true; else if (Pane != null && Pane.ActiveContent != Content) visible = false; else visible = Form.Visible; if (Form.Visible != visible) Form.Visible = visible; } private void SetParent(Control value) { if (Form.Parent == value) return; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! bool bRestoreFocus = false; if (Form.ContainsFocus) { // Suggested as a fix for a memory leak by bugreports if (value == null && !IsFloat) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.GiveUpFocus(this.Content); } } else { DockPanel.SaveFocus(); bRestoreFocus = true; } } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Form.Parent = value; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (bRestoreFocus) Activate(); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } public void Show() { if (DockPanel == null) Form.Show(); else Show(DockPanel); } public void Show(DockPanel dockPanel) { if (dockPanel == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); if (DockState == DockState.Unknown) Show(dockPanel, DefaultShowState); else if (DockPanel != dockPanel) Show(dockPanel, DockState == DockState.Hidden ? m_visibleState : DockState); else Activate(); } public void Show(DockPanel dockPanel, DockState dockState) { if (dockPanel == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); if (dockState == DockState.Unknown || dockState == DockState.Hidden) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidDockState)); dockPanel.SuspendLayout(true); DockPanel = dockPanel; if (dockState == DockState.Float) { if (FloatPane == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Float, true); } else if (PanelPane == null) { DockPane paneExisting = null; foreach (DockPane pane in DockPanel.Panes) if (pane.DockState == dockState) { if (paneExisting == null || pane.IsActivated) paneExisting = pane; if (pane.IsActivated) break; } if (paneExisting == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, dockState, true); else Pane = paneExisting; } DockState = dockState; dockPanel.ResumeLayout(true, true); //we'll resume the layout before activating to ensure that the position Activate(); //and size of the form are finally processed before the form is shown } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public void Show(DockPanel dockPanel, Rectangle floatWindowBounds) { if (dockPanel == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); dockPanel.SuspendLayout(true); DockPanel = dockPanel; if (FloatPane == null) { IsHidden = true; // to reduce the screen flicker FloatPane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Float, false); FloatPane.FloatWindow.StartPosition = FormStartPosition.Manual; } FloatPane.FloatWindow.Bounds = floatWindowBounds; Show(dockPanel, DockState.Float); Activate(); dockPanel.ResumeLayout(true, true); } public void Show(DockPane pane, IDockContent beforeContent) { if (pane == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullPane)); if (beforeContent != null && pane.Contents.IndexOf(beforeContent) == -1) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidBeforeContent)); pane.DockPanel.SuspendLayout(true); DockPanel = pane.DockPanel; Pane = pane; pane.SetContentIndex(Content, pane.Contents.IndexOf(beforeContent)); Show(); pane.DockPanel.ResumeLayout(true, true); } public void Show(DockPane previousPane, DockAlignment alignment, double proportion) { if (previousPane == null) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidPrevPane)); if (DockHelper.IsDockStateAutoHide(previousPane.DockState)) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidPrevPane)); previousPane.DockPanel.SuspendLayout(true); DockPanel = previousPane.DockPanel; DockPanel.DockPaneFactory.CreateDockPane(Content, previousPane, alignment, proportion, true); Show(); previousPane.DockPanel.ResumeLayout(true, true); } public void Close() { DockPanel dockPanel = DockPanel; if (dockPanel != null) dockPanel.SuspendLayout(true); Form.Close(); if (dockPanel != null) dockPanel.ResumeLayout(true, true); } private DockPaneStripBase.Tab m_tab = null; internal DockPaneStripBase.Tab GetTab(DockPaneStripBase dockPaneStrip) { if (m_tab == null) m_tab = dockPaneStrip.CreateTab(Content); return m_tab; } private IDisposable m_autoHideTab = null; internal IDisposable AutoHideTab { get { return m_autoHideTab; } set { m_autoHideTab = value; } } #region Events private static readonly object DockStateChangedEvent = new object(); public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } #endregion private void Form_Disposed(object sender, EventArgs e) { Dispose(); } private void Form_TextChanged(object sender, EventArgs e) { if (DockHelper.IsDockStateAutoHide(DockState)) DockPanel.RefreshAutoHideStrip(); else if (Pane != null) { if (Pane.FloatWindow != null) Pane.FloatWindow.SetText(); Pane.RefreshChanges(); } } private bool m_flagClipWindow = false; internal bool FlagClipWindow { get { return m_flagClipWindow; } set { if (m_flagClipWindow == value) return; m_flagClipWindow = value; if (m_flagClipWindow) Form.Region = new Region(Rectangle.Empty); else Form.Region = null; } } private ContextMenuStrip m_tabPageContextMenuStrip = null; public ContextMenuStrip TabPageContextMenuStrip { get { return m_tabPageContextMenuStrip; } set { m_tabPageContextMenuStrip = value; } } #region IDockDragSource Members Control IDragSource.DragControl { get { return Form; } } bool IDockDragSource.CanDockTo(DockPane pane) { if (!IsDockStateValid(pane.DockState)) return false; if (Pane == pane && pane.DisplayingContents.Count == 1) return false; return true; } Rectangle IDockDragSource.BeginDrag(Point ptMouse) { Size size; DockPane floatPane = this.FloatPane; if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1) size = DockPanel.DefaultFloatWindowSize; else size = floatPane.FloatWindow.Size; Point location; Rectangle rectPane = Pane.ClientRectangle; if (DockState == DockState.Document) { if (Pane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) location = new Point(rectPane.Left, rectPane.Bottom - size.Height); else location = new Point(rectPane.Left, rectPane.Top); } else { location = new Point(rectPane.Left, rectPane.Bottom); location.Y -= size.Height; } location = Pane.PointToScreen(location); if (ptMouse.X > location.X + size.Width) location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize; return new Rectangle(location, size); } void IDockDragSource.EndDrag() { } public void FloatAt(Rectangle floatWindowBounds) { // TODO: where is the pane used? DockPane pane = DockPanel.DockPaneFactory.CreateDockPane(Content, floatWindowBounds, true); } public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) { if (dockStyle == DockStyle.Fill) { bool samePane = (Pane == pane); if (!samePane) Pane = pane; if (contentIndex == -1 || !samePane) pane.SetContentIndex(Content, contentIndex); else { DockContentCollection contents = pane.Contents; int oldIndex = contents.IndexOf(Content); int newIndex = contentIndex; if (oldIndex < newIndex) { newIndex += 1; if (newIndex > contents.Count -1) newIndex = -1; } pane.SetContentIndex(Content, newIndex); } } else { DockPane paneFrom = DockPanel.DockPaneFactory.CreateDockPane(Content, pane.DockState, true); INestedPanesContainer container = pane.NestedPanesContainer; if (dockStyle == DockStyle.Left) paneFrom.DockTo(container, pane, DockAlignment.Left, 0.5); else if (dockStyle == DockStyle.Right) paneFrom.DockTo(container, pane, DockAlignment.Right, 0.5); else if (dockStyle == DockStyle.Top) paneFrom.DockTo(container, pane, DockAlignment.Top, 0.5); else if (dockStyle == DockStyle.Bottom) paneFrom.DockTo(container, pane, DockAlignment.Bottom, 0.5); paneFrom.DockState = pane.DockState; } } public void DockTo(DockPanel panel, DockStyle dockStyle) { if (panel != DockPanel) throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel"); DockPane pane; if (dockStyle == DockStyle.Top) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockTop, true); else if (dockStyle == DockStyle.Bottom) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockBottom, true); else if (dockStyle == DockStyle.Left) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockLeft, true); else if (dockStyle == DockStyle.Right) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockRight, true); else if (dockStyle == DockStyle.Fill) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Document, true); else return; } #endregion } }
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 Hyperion.WebAPI.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; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // StringExpressionSet // // <OWNER>[....]</OWNER> // namespace System.Security.Util { using System.Text; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Globalization; using System.Runtime.Versioning; using System.IO; using System.Diagnostics.Contracts; [Serializable] internal class StringExpressionSet { // This field, as well as the expressions fields below are critical since they may contain // canonicalized full path data potentially built out of relative data passed as input to the // StringExpressionSet. Full trust code using the string expression set needs to ensure that before // exposing this data out to partial trust, they protect against this. Possibilities include: // // 1. Using the throwOnRelative flag // 2. Ensuring that the partial trust code has permission to see full path data // 3. Not using this set for paths (eg EnvironmentStringExpressionSet) // [SecurityCritical] protected ArrayList m_list; protected bool m_ignoreCase; [SecurityCritical] protected String m_expressions; [SecurityCritical] protected String[] m_expressionsArray; protected bool m_throwOnRelative; protected static readonly char[] m_separators = { ';' }; protected static readonly char[] m_trimChars = { ' ' }; #if !PLATFORM_UNIX protected static readonly char m_directorySeparator = '\\'; protected static readonly char m_alternateDirectorySeparator = '/'; #else protected static readonly char m_directorySeparator = '/'; protected static readonly char m_alternateDirectorySeparator = '\\'; #endif // !PLATFORM_UNIX public StringExpressionSet() : this( true, null, false ) { } public StringExpressionSet( String str ) : this( true, str, false ) { } public StringExpressionSet( bool ignoreCase, bool throwOnRelative ) : this( ignoreCase, null, throwOnRelative ) { } [System.Security.SecuritySafeCritical] // auto-generated public StringExpressionSet( bool ignoreCase, String str, bool throwOnRelative ) { m_list = null; m_ignoreCase = ignoreCase; m_throwOnRelative = throwOnRelative; if (str == null) m_expressions = null; else AddExpressions( str ); } protected virtual StringExpressionSet CreateNewEmpty() { return new StringExpressionSet(); } [SecuritySafeCritical] public virtual StringExpressionSet Copy() { // SafeCritical: just copying this value around, not leaking it StringExpressionSet copy = CreateNewEmpty(); if (this.m_list != null) copy.m_list = new ArrayList(this.m_list); copy.m_expressions = this.m_expressions; copy.m_ignoreCase = this.m_ignoreCase; copy.m_throwOnRelative = this.m_throwOnRelative; return copy; } public void SetThrowOnRelative( bool throwOnRelative ) { this.m_throwOnRelative = throwOnRelative; } private static String StaticProcessWholeString( String str ) { return str.Replace( m_alternateDirectorySeparator, m_directorySeparator ); } private static String StaticProcessSingleString( String str ) { return str.Trim( m_trimChars ); } protected virtual String ProcessWholeString( String str ) { return StaticProcessWholeString(str); } protected virtual String ProcessSingleString( String str ) { return StaticProcessSingleString(str); } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public void AddExpressions( String str ) { if (str == null) throw new ArgumentNullException( "str" ); Contract.EndContractBlock(); if (str.Length == 0) return; str = ProcessWholeString( str ); if (m_expressions == null) m_expressions = str; else m_expressions = m_expressions + m_separators[0] + str; m_expressionsArray = null; // We have to parse the string and compute the list here. // The logic in this class tries to delay this parsing but // since operations like IsSubsetOf are called during // demand evaluation, it is not safe to delay this step // as that would cause concurring threads to update the object // at the same time. The CheckList operation should ideally be // removed from this class, but for the sake of keeping the // changes to a minimum here, we simply make sure m_list // cannot be null by parsing m_expressions eagerly. String[] arystr = Split( str ); if (m_list == null) m_list = new ArrayList(); for (int index = 0; index < arystr.Length; ++index) { if (arystr[index] != null && !arystr[index].Equals( "" )) { String temp = ProcessSingleString( arystr[index] ); int indexOfNull = temp.IndexOf( '\0' ); if (indexOfNull != -1) temp = temp.Substring( 0, indexOfNull ); if (temp != null && !temp.Equals( "" )) { if (m_throwOnRelative) { if (Path.IsRelative(temp)) { throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); } temp = CanonicalizePath( temp ); } m_list.Add( temp ); } } } Reduce(); } [System.Security.SecurityCritical] // auto-generated public void AddExpressions( String[] str, bool checkForDuplicates, bool needFullPath ) { AddExpressions(CreateListFromExpressions(str, needFullPath), checkForDuplicates); } [System.Security.SecurityCritical] // auto-generated public void AddExpressions( ArrayList exprArrayList, bool checkForDuplicates) { Contract.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" ); m_expressionsArray = null; m_expressions = null; if (m_list != null) m_list.AddRange(exprArrayList); else m_list = new ArrayList(exprArrayList); if (checkForDuplicates) Reduce(); } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] internal static ArrayList CreateListFromExpressions(String[] str, bool needFullPath) { if (str == null) { throw new ArgumentNullException( "str" ); } Contract.EndContractBlock(); ArrayList retArrayList = new ArrayList(); for (int index = 0; index < str.Length; ++index) { if (str[index] == null) throw new ArgumentNullException( "str" ); String oneString = StaticProcessWholeString( str[index] ); if (oneString != null && oneString.Length != 0) { String temp = StaticProcessSingleString( oneString); int indexOfNull = temp.IndexOf( '\0' ); if (indexOfNull != -1) temp = temp.Substring( 0, indexOfNull ); if (temp != null && temp.Length != 0) { if (Path.IsRelative(temp)) { throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); } temp = CanonicalizePath( temp, needFullPath ); retArrayList.Add( temp ); } } } return retArrayList; } [System.Security.SecurityCritical] // auto-generated protected void CheckList() { if (m_list == null && m_expressions != null) { CreateList(); } } protected String[] Split( String expressions ) { if (m_throwOnRelative) { List<String> tempList = new List<String>(); String[] quoteSplit = expressions.Split( '\"' ); for (int i = 0; i < quoteSplit.Length; ++i) { if (i % 2 == 0) { String[] semiSplit = quoteSplit[i].Split( ';' ); for (int j = 0; j < semiSplit.Length; ++j) { if (semiSplit[j] != null && !semiSplit[j].Equals( "" )) tempList.Add( semiSplit[j] ); } } else { tempList.Add( quoteSplit[i] ); } } String[] finalArray = new String[tempList.Count]; IEnumerator enumerator = tempList.GetEnumerator(); int index = 0; while (enumerator.MoveNext()) { finalArray[index++] = (String)enumerator.Current; } return finalArray; } else { return expressions.Split( m_separators ); } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] protected void CreateList() { String[] expressionsArray = Split( m_expressions ); m_list = new ArrayList(); for (int index = 0; index < expressionsArray.Length; ++index) { if (expressionsArray[index] != null && !expressionsArray[index].Equals( "" )) { String temp = ProcessSingleString( expressionsArray[index] ); int indexOfNull = temp.IndexOf( '\0' ); if (indexOfNull != -1) temp = temp.Substring( 0, indexOfNull ); if (temp != null && !temp.Equals( "" )) { if (m_throwOnRelative) { if (Path.IsRelative(temp)) { throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); } temp = CanonicalizePath( temp ); } m_list.Add( temp ); } } } } [SecuritySafeCritical] public bool IsEmpty() { // SafeCritical: we're just showing that the expressions are empty, the sensitive portion is their // contents - not the existence of the contents if (m_list == null) { return m_expressions == null; } else { return m_list.Count == 0; } } [System.Security.SecurityCritical] // auto-generated public bool IsSubsetOf( StringExpressionSet ses ) { if (this.IsEmpty()) return true; if (ses == null || ses.IsEmpty()) return false; CheckList(); ses.CheckList(); for (int index = 0; index < this.m_list.Count; ++index) { if (!StringSubsetStringExpression( (String)this.m_list[index], ses, m_ignoreCase )) { return false; } } return true; } [System.Security.SecurityCritical] // auto-generated public bool IsSubsetOfPathDiscovery( StringExpressionSet ses ) { if (this.IsEmpty()) return true; if (ses == null || ses.IsEmpty()) return false; CheckList(); ses.CheckList(); for (int index = 0; index < this.m_list.Count; ++index) { if (!StringSubsetStringExpressionPathDiscovery( (String)this.m_list[index], ses, m_ignoreCase )) { return false; } } return true; } [System.Security.SecurityCritical] // auto-generated public StringExpressionSet Union( StringExpressionSet ses ) { // If either set is empty, the union represents a copy of the other. if (ses == null || ses.IsEmpty()) return this.Copy(); if (this.IsEmpty()) return ses.Copy(); CheckList(); ses.CheckList(); // Perform the union // note: insert smaller set into bigger set to reduce needed comparisons StringExpressionSet bigger = ses.m_list.Count > this.m_list.Count ? ses : this; StringExpressionSet smaller = ses.m_list.Count <= this.m_list.Count ? ses : this; StringExpressionSet unionSet = bigger.Copy(); unionSet.Reduce(); for (int index = 0; index < smaller.m_list.Count; ++index) { unionSet.AddSingleExpressionNoDuplicates( (String)smaller.m_list[index] ); } unionSet.GenerateString(); return unionSet; } [System.Security.SecurityCritical] // auto-generated public StringExpressionSet Intersect( StringExpressionSet ses ) { // If either set is empty, the intersection is empty if (this.IsEmpty() || ses == null || ses.IsEmpty()) return CreateNewEmpty(); CheckList(); ses.CheckList(); // Do the intersection for real StringExpressionSet intersectSet = CreateNewEmpty(); for (int this_index = 0; this_index < this.m_list.Count; ++this_index) { for (int ses_index = 0; ses_index < ses.m_list.Count; ++ses_index) { if (StringSubsetString( (String)this.m_list[this_index], (String)ses.m_list[ses_index], m_ignoreCase )) { if (intersectSet.m_list == null) { intersectSet.m_list = new ArrayList(); } intersectSet.AddSingleExpressionNoDuplicates( (String)this.m_list[this_index] ); } else if (StringSubsetString( (String)ses.m_list[ses_index], (String)this.m_list[this_index], m_ignoreCase )) { if (intersectSet.m_list == null) { intersectSet.m_list = new ArrayList(); } intersectSet.AddSingleExpressionNoDuplicates( (String)ses.m_list[ses_index] ); } } } intersectSet.GenerateString(); return intersectSet; } [SecuritySafeCritical] protected void GenerateString() { // SafeCritical - moves critical data around, but doesn't expose it out if (m_list != null) { StringBuilder sb = new StringBuilder(); IEnumerator enumerator = this.m_list.GetEnumerator(); bool first = true; while (enumerator.MoveNext()) { if (!first) sb.Append( m_separators[0] ); else first = false; String currentString = (String)enumerator.Current; if (currentString != null) { int indexOfSeparator = currentString.IndexOf( m_separators[0] ); if (indexOfSeparator != -1) sb.Append( '\"' ); sb.Append( currentString ); if (indexOfSeparator != -1) sb.Append( '\"' ); } } m_expressions = sb.ToString(); } else { m_expressions = null; } } // We don't override ToString since that API must be either transparent or safe citical. If the // expressions contain paths that were canonicalized and expanded from the input that would cause // information disclosure, so we instead only expose this out to trusted code that can ensure they // either don't leak the information or required full path information. [SecurityCritical] public string UnsafeToString() { CheckList(); Reduce(); GenerateString(); return m_expressions; } [SecurityCritical] public String[] UnsafeToStringArray() { if (m_expressionsArray == null && m_list != null) { m_expressionsArray = (String[])m_list.ToArray(typeof(String)); } return m_expressionsArray; } //------------------------------- // protected static helper functions //------------------------------- [SecurityCritical] private bool StringSubsetStringExpression( String left, StringExpressionSet right, bool ignoreCase ) { for (int index = 0; index < right.m_list.Count; ++index) { if (StringSubsetString( left, (String)right.m_list[index], ignoreCase )) { return true; } } return false; } [SecurityCritical] private static bool StringSubsetStringExpressionPathDiscovery( String left, StringExpressionSet right, bool ignoreCase ) { for (int index = 0; index < right.m_list.Count; ++index) { if (StringSubsetStringPathDiscovery( left, (String)right.m_list[index], ignoreCase )) { return true; } } return false; } protected virtual bool StringSubsetString( String left, String right, bool ignoreCase ) { StringComparison strComp = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); if (right == null || left == null || right.Length == 0 || left.Length == 0 || right.Length > left.Length) { return false; } else if (right.Length == left.Length) { // if they are equal in length, just do a normal compare return String.Compare( right, left, strComp) == 0; } else if (left.Length - right.Length == 1 && left[left.Length-1] == m_directorySeparator) { return String.Compare( left, 0, right, 0, right.Length, strComp) == 0; } else if (right[right.Length-1] == m_directorySeparator) { // right is definitely a directory, just do a substring compare return String.Compare( right, 0, left, 0, right.Length, strComp) == 0; } else if (left[right.Length] == m_directorySeparator) { // left is hinting at being a subdirectory on right, do substring compare to make find out return String.Compare( right, 0, left, 0, right.Length, strComp) == 0; } else { return false; } } protected static bool StringSubsetStringPathDiscovery( String left, String right, bool ignoreCase ) { StringComparison strComp = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); if (right == null || left == null || right.Length == 0 || left.Length == 0) { return false; } else if (right.Length == left.Length) { // if they are equal in length, just do a normal compare return String.Compare( right, left, strComp) == 0; } else { String shortString, longString; if (right.Length < left.Length) { shortString = right; longString = left; } else { shortString = left; longString = right; } if (String.Compare( shortString, 0, longString, 0, shortString.Length, strComp) != 0) { return false; } #if !PLATFORM_UNIX if (shortString.Length == 3 && shortString.EndsWith( ":\\", StringComparison.Ordinal ) && ((shortString[0] >= 'A' && shortString[0] <= 'Z') || (shortString[0] >= 'a' && shortString[0] <= 'z'))) #else if (shortString.Length == 1 && shortString[0]== m_directorySeparator) #endif // !PLATFORM_UNIX return true; return longString[shortString.Length] == m_directorySeparator; } } //------------------------------- // protected helper functions //------------------------------- [SecuritySafeCritical] protected void AddSingleExpressionNoDuplicates( String expression ) { // SafeCritical: We're not exposing out the string sets, just allowing modification of them int index = 0; m_expressionsArray = null; m_expressions = null; if (this.m_list == null) this.m_list = new ArrayList(); while (index < this.m_list.Count) { if (StringSubsetString( (String)this.m_list[index], expression, m_ignoreCase )) { this.m_list.RemoveAt( index ); } else if (StringSubsetString( expression, (String)this.m_list[index], m_ignoreCase )) { return; } else { index++; } } this.m_list.Add( expression ); } [System.Security.SecurityCritical] // auto-generated protected void Reduce() { CheckList(); if (this.m_list == null) return; int j; for (int i = 0; i < this.m_list.Count - 1; i++) { j = i + 1; while (j < this.m_list.Count) { if (StringSubsetString( (String)this.m_list[j], (String)this.m_list[i], m_ignoreCase )) { this.m_list.RemoveAt( j ); } else if (StringSubsetString( (String)this.m_list[i], (String)this.m_list[j], m_ignoreCase )) { // write the value at j into position i, delete the value at position j and keep going. this.m_list[i] = this.m_list[j]; this.m_list.RemoveAt( j ); j = i + 1; } else { j++; } } } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void GetLongPathName( String path, StringHandleOnStack retLongPath ); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] internal static String CanonicalizePath( String path ) { return CanonicalizePath( path, true ); } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] internal static String CanonicalizePath( String path, bool needFullPath ) { #if !PLATFORM_UNIX if (path.IndexOf( '~' ) != -1) { string longPath = null; GetLongPathName(path, JitHelpers.GetStringHandleOnStack(ref longPath)); path = (longPath != null) ? longPath : path; } if (path.IndexOf( ':', 2 ) != -1) throw new NotSupportedException( Environment.GetResourceString( "Argument_PathFormatNotSupported" ) ); #endif // !PLATFORM_UNIX if (needFullPath) { String newPath = System.IO.Path.GetFullPathInternal( path ); if (path.EndsWith( m_directorySeparator + ".", StringComparison.Ordinal )) { if (newPath.EndsWith( m_directorySeparator )) { newPath += "."; } else { newPath += m_directorySeparator + "."; } } return newPath; } else return path; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; internal static class IOInputs { // see: http://msdn.microsoft.com/en-us/library/aa365247.aspx private static readonly char[] s_invalidFileNameChars = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? new char[] { '\"', '<', '>', '|', '\0', (Char)1, (Char)2, (Char)3, (Char)4, (Char)5, (Char)6, (Char)7, (Char)8, (Char)9, (Char)10, (Char)11, (Char)12, (Char)13, (Char)14, (Char)15, (Char)16, (Char)17, (Char)18, (Char)19, (Char)20, (Char)21, (Char)22, (Char)23, (Char)24, (Char)25, (Char)26, (Char)27, (Char)28, (Char)29, (Char)30, (Char)31, '*', '?' } : new char[] { '\0' }; public static bool SupportsSettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } } public static bool SupportsGettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) | RuntimeInformation.IsOSPlatform(OSPlatform.OSX); } } // Max path length (minus trailing \0). Unix values vary system to system; just using really long values here likely to be more than on the average system. public static readonly int MaxPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 259 : 10000; // Same as MaxPath on Unix public static readonly int MaxLongPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MaxExtendedPath : MaxPath; // Windows specific, this is the maximum length that can be passed to APIs taking directory names, such as Directory.CreateDirectory & Directory.Move. // Does not include the trailing \0. // We now do the appropriate wrapping to allow creating longer directories. Like MaxPath, this is a legacy restriction. public static readonly int MaxDirectory = 247; // Windows specific, this is the maximum length that can be passed using extended syntax. Does not include the trailing \0. public static readonly int MaxExtendedPath = short.MaxValue - 1; public const int MaxComponent = 255; public const string ExtendedPrefix = @"\\?\"; public const string ExtendedUncPrefix = @"\\?\UNC\"; public static IEnumerable<string> GetValidPathComponentNames() { yield return Path.GetRandomFileName(); yield return "!@#$%^&"; yield return "\x65e5\x672c\x8a9e"; yield return "A"; yield return " A"; yield return " A"; yield return "FileName"; yield return "FileName.txt"; yield return " FileName"; yield return " FileName.txt"; yield return " FileName"; yield return " FileName.txt"; yield return "This is a valid component name"; yield return "This is a valid component name.txt"; yield return "V1.0.0.0000"; } public static IEnumerable<string> GetControlWhiteSpace() { yield return "\t"; yield return "\t\t"; yield return "\t\t\t"; yield return "\n"; yield return "\n\n"; yield return "\n\n\n"; yield return "\t\n"; yield return "\t\n\t\n"; yield return "\n\t\n"; yield return "\n\t\n\t"; } public static IEnumerable<string> GetSimpleWhiteSpace() { yield return " "; yield return " "; yield return " "; yield return " "; yield return " "; } public static IEnumerable<string> GetWhiteSpace() { return GetControlWhiteSpace().Concat(GetSimpleWhiteSpace()); } public static IEnumerable<string> GetUncPathsWithoutShareName() { foreach (char slash in new[] { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar }) { string slashes = new string(slash, 2); yield return slashes; yield return slashes + " "; yield return slashes + new string(slash, 5); yield return slashes + "S"; yield return slashes + "S "; yield return slashes + "LOCALHOST"; yield return slashes + "LOCALHOST " + slash; yield return slashes + "LOCALHOST " + new string(slash, 2); yield return slashes + "LOCALHOST" + slash + " "; yield return slashes + "LOCALHOST" + slash + slash + " "; } } public static IEnumerable<string> GetPathsWithReservedDeviceNames() { string root = Path.GetPathRoot(Directory.GetCurrentDirectory()); foreach (string deviceName in GetReservedDeviceNames()) { yield return deviceName; yield return Path.Combine(root, deviceName); yield return Path.Combine(root, "Directory", deviceName); yield return Path.Combine(new string(Path.DirectorySeparatorChar, 2), "LOCALHOST", deviceName); } } public static IEnumerable<string> GetPathsWithAlternativeDataStreams() { yield return @"AA:"; yield return @"AAA:"; yield return @"AA:A"; yield return @"AAA:A"; yield return @"AA:AA"; yield return @"AAA:AA"; yield return @"AA:AAA"; yield return @"AAA:AAA"; yield return @"AA:FileName"; yield return @"AAA:FileName"; yield return @"AA:FileName.txt"; yield return @"AAA:FileName.txt"; yield return @"A:FileName.txt:"; yield return @"AA:FileName.txt:AA"; yield return @"AAA:FileName.txt:AAA"; yield return @"C:\:"; yield return @"C:\:FileName"; yield return @"C:\:FileName.txt"; yield return @"C:\fileName:"; yield return @"C:\fileName:FileName.txt"; yield return @"C:\fileName:FileName.txt:"; yield return @"C:\fileName:FileName.txt:AA"; yield return @"C:\fileName:FileName.txt:AAA"; yield return @"ftp://fileName:FileName.txt:AAA"; } public static IEnumerable<string> GetPathsWithInvalidColons() { // Windows specific. We document that these return NotSupportedException. yield return @":"; yield return @" :"; yield return @" :"; yield return @"C::"; yield return @"C::FileName"; yield return @"C::FileName.txt"; yield return @"C::FileName.txt:"; yield return @"C::FileName.txt::"; yield return @":f"; yield return @":filename"; yield return @"file:"; yield return @"file:file"; yield return @"http:"; yield return @"http:/"; yield return @"http://"; yield return @"http://www"; yield return @"http://www.microsoft.com"; yield return @"http://www.microsoft.com/index.html"; yield return @"http://server"; yield return @"http://server/"; yield return @"http://server/home"; yield return @"file://"; yield return @"file:///C|/My Documents/ALetter.html"; } public static IEnumerable<string> GetPathsWithInvalidCharacters() { // NOTE: That I/O treats "file"/http" specially and throws ArgumentException. // Otherwise, it treats all other urls as alternative data streams if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // alternate data streams, drive labels, etc. { yield return "\0"; yield return "middle\0path"; yield return "trailing\0"; yield return @"\\?\"; yield return @"\\?\UNC\"; yield return @"\\?\UNC\LOCALHOST"; } else { yield return "\0"; yield return "middle\0path"; yield return "trailing\0"; } foreach (char c in s_invalidFileNameChars) { yield return c.ToString(); } } public static IEnumerable<string> GetPathsWithComponentLongerThanMaxComponent() { // While paths themselves can be up to and including 32,000 characters, most volumes // limit each component of the path to a total of 255 characters. string component = new string('s', MaxComponent + 1); yield return String.Format(@"C:\{0}", component); yield return String.Format(@"C:\{0}\Filename.txt", component); yield return String.Format(@"C:\{0}\Filename.txt\", component); yield return String.Format(@"\\{0}\Share", component); yield return String.Format(@"\\LOCALHOST\{0}", component); yield return String.Format(@"\\LOCALHOST\{0}\FileName.txt", component); yield return String.Format(@"\\LOCALHOST\Share\{0}", component); } public static IEnumerable<string> GetPathsLongerThanMaxDirectory(string rootPath) { yield return GetLongPath(rootPath, MaxDirectory + 1); yield return GetLongPath(rootPath, MaxDirectory + 2); yield return GetLongPath(rootPath, MaxDirectory + 3); } public static IEnumerable<string> GetPathsLongerThanMaxPath(string rootPath, bool useExtendedSyntax = false) { yield return GetLongPath(rootPath, MaxPath + 1, useExtendedSyntax); yield return GetLongPath(rootPath, MaxPath + 2, useExtendedSyntax); yield return GetLongPath(rootPath, MaxPath + 3, useExtendedSyntax); } public static IEnumerable<string> GetPathsLongerThanMaxLongPath(string rootPath, bool useExtendedSyntax = false) { yield return GetLongPath(rootPath, MaxExtendedPath + 1 - (useExtendedSyntax ? 0 : ExtendedPrefix.Length), useExtendedSyntax); yield return GetLongPath(rootPath, MaxExtendedPath + 2 - (useExtendedSyntax ? 0 : ExtendedPrefix.Length), useExtendedSyntax); } private static string GetLongPath(string rootPath, int characterCount, bool extended = false) { return IOServices.GetPath(rootPath, characterCount, extended).FullPath; } public static IEnumerable<string> GetReservedDeviceNames() { // See: http://msdn.microsoft.com/en-us/library/aa365247.aspx yield return "CON"; yield return "AUX"; yield return "NUL"; yield return "PRN"; yield return "COM1"; yield return "COM2"; yield return "COM3"; yield return "COM4"; yield return "COM5"; yield return "COM6"; yield return "COM7"; yield return "COM8"; yield return "COM9"; yield return "LPT1"; yield return "LPT2"; yield return "LPT3"; yield return "LPT4"; yield return "LPT5"; yield return "LPT6"; yield return "LPT7"; yield return "LPT8"; yield return "LPT9"; } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Markup.XmlnsDictionary.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Markup { public partial class XmlnsDictionary : System.Collections.IDictionary, System.Collections.ICollection, System.Collections.IEnumerable, System.Xaml.IXamlNamespaceResolver { #region Methods and constructors public void Add(string prefix, string xmlNamespace) { } public void Add(Object prefix, Object xmlNamespace) { } public void Clear() { } public bool Contains(Object key) { return default(bool); } public void CopyTo(System.Collections.DictionaryEntry[] array, int index) { Contract.Requires(array != null); Contract.Requires(index >= 0); } public void CopyTo(Array array, int index) { } public string DefaultNamespace() { Contract.Ensures(Contract.Result<string>() != null); return default(string); } protected System.Collections.IDictionaryEnumerator GetDictionaryEnumerator() { Contract.Ensures(Contract.Result<System.Collections.IDictionaryEnumerator>() != null); return default(System.Collections.IDictionaryEnumerator); } protected System.Collections.IEnumerator GetEnumerator() { Contract.Ensures(Contract.Result<System.Collections.IEnumerator>() != null); return default(System.Collections.IEnumerator); } public string GetNamespace(string prefix) { return default(string); } public IEnumerable<System.Xaml.NamespaceDeclaration> GetNamespacePrefixes() { return default(IEnumerable<System.Xaml.NamespaceDeclaration>); } public string LookupNamespace(string prefix) { return default(string); } public string LookupPrefix(string xmlNamespace) { return default(string); } public void PopScope() { } public void PushScope() { Contract.Ensures(!this.IsReadOnly); } public void Remove(string prefix) { } public void Remove(Object prefix) { } public void Seal() { } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public XmlnsDictionary() { } public XmlnsDictionary(System.Windows.Markup.XmlnsDictionary xmlnsDictionary) { Contract.Ensures(0 <= xmlnsDictionary.Count); } #endregion #region Properties and indexers public int Count { get { return default(int); } } public bool IsFixedSize { get { return default(bool); } } public bool IsReadOnly { get { return default(bool); } } public bool IsSynchronized { get { return default(bool); } } public string this [string prefix] { get { return default(string); } set { } } public Object this [Object prefix] { get { return default(Object); } set { } } public System.Collections.ICollection Keys { get { return default(System.Collections.ICollection); } } public bool Sealed { get { return default(bool); } } public Object SyncRoot { get { return default(Object); } } public System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.NetworkInformation; using System.Threading.Tasks; using Baseline; using Baseline.ImTools; using Jasper.Configuration; using Jasper.Persistence.Durability; using Jasper.Runtime; using Jasper.Runtime.Routing; using Jasper.Runtime.WorkerQueues; using Jasper.Transports.Local; using Jasper.Transports.Sending; using Jasper.Util; namespace Jasper.Transports { public class TransportRuntime : ITransportRuntime { private readonly IList<IDisposable> _disposables = new List<IDisposable>(); private readonly IList<ISubscriber> _subscribers = new List<ISubscriber>(); private readonly object _channelLock = new object(); private ImHashMap<Uri, ISendingAgent> _senders = ImHashMap<Uri, ISendingAgent>.Empty; private readonly IMessagingRoot _root; private TransportCollection _transports; public TransportRuntime(IMessagingRoot root) { _root = root; _transports = root.Options.Transports; } public void Initialize() { foreach (var transport in _transports) { transport.Initialize(_root); foreach (var endpoint in transport.Endpoints()) { endpoint.Root = _root; // necessary to locate serialization } } foreach (var transport in _transports) { transport.StartSenders(_root, this); } foreach (var transport in _transports) { transport.StartListeners(_root, this); } foreach (var subscriber in _transports.Subscribers) { _subscribers.Fill(subscriber); } } public ISendingAgent AddSubscriber(Uri replyUri, ISender sender, Endpoint endpoint) { try { var agent = buildSendingAgent(sender, endpoint); agent.ReplyUri = replyUri; endpoint.Agent = agent; if (sender is ISenderRequiresCallback senderRequiringCallback && agent is ISenderCallback callbackAgent) { senderRequiringCallback.RegisterCallback(callbackAgent); } AddSendingAgent(agent); AddSubscriber(endpoint); return agent; } catch (Exception e) { throw new TransportEndpointException(sender.Destination, "Could not build sending sendingAgent. See inner exception.", e); } } private ISendingAgent buildSendingAgent(ISender sender, Endpoint endpoint) { // This is for the stub transport in the Storyteller specs if (sender is ISendingAgent a) return a; switch (endpoint.Mode) { case EndpointMode.Durable: return new DurableSendingAgent(sender, _root.Settings, _root.TransportLogger, _root.MessageLogger, _root.Persistence, endpoint); case EndpointMode.BufferedInMemory: return new LightweightSendingAgent(_root.TransportLogger, _root.MessageLogger, sender, _root.Settings, endpoint); case EndpointMode.Inline: return new InlineSendingAgent(sender, endpoint, _root.MessageLogger, _root.Settings); } throw new InvalidOperationException(); } public void AddSendingAgent(ISendingAgent sendingAgent) { _senders = _senders.AddOrUpdate(sendingAgent.Destination, sendingAgent); } public void AddSubscriber(ISubscriber subscriber) { _subscribers.Fill(subscriber); } private ImHashMap<string, ISendingAgent> _localSenders = ImHashMap<string, ISendingAgent>.Empty; public ISendingAgent AgentForLocalQueue(string queueName) { queueName = queueName ?? TransportConstants.Default; if (_localSenders.TryFind(queueName, out var agent)) { return agent; } agent = GetOrBuildSendingAgent($"local://{queueName}".ToUri()); _localSenders = _localSenders.AddOrUpdate(queueName, agent); return agent; } public ISendingAgent GetOrBuildSendingAgent(Uri address) { if (address == null) throw new ArgumentNullException(nameof(address)); if (_senders.TryFind(address, out var agent)) return agent; lock (_channelLock) { return !_senders.TryFind(address, out agent) ? buildSendingAgent(address) : agent; } } private ISendingAgent buildSendingAgent(Uri uri) { var transport = _transports.TransportForScheme(uri.Scheme); if (transport == null) { throw new InvalidOperationException($"There is no known transport type that can send to the Destination {uri}"); } if (uri.Scheme == TransportConstants.Local) { var local = (LocalTransport)transport; var agent = local.AddSenderForDestination(uri, _root, this); agent.Endpoint.Root = _root; // This is important for serialization AddSendingAgent(agent); return agent; } else { var endpoint = transport.GetOrCreateEndpoint(uri); endpoint.Root ??= _root; // This is important for serialization return endpoint.StartSending(_root, _root.Runtime, transport.ReplyEndpoint()?.ReplyUri()); } } public void AddListener(IListener listener, Endpoint settings) { IDisposable worker = null; switch (settings.Mode) { case EndpointMode.Durable: worker = new DurableWorkerQueue(settings, _root.Pipeline, _root.Settings, _root.Persistence, _root.TransportLogger); break; case EndpointMode.BufferedInMemory: worker = new LightweightWorkerQueue(settings, _root.TransportLogger, _root.Pipeline, _root.Settings); break; case EndpointMode.Inline: worker = new InlineWorkerQueue(_root.Pipeline, _root.TransportLogger, listener, _root.Settings); break; } if (worker is IWorkerQueue q) q.StartListening(listener); _disposables.Add(worker); } public Task Stop() { // TODO -- this needs to be draining the senders and listeners throw new NotImplementedException(); } public ISubscriber[] FindSubscribersForMessageType(Type messageType) { return _subscribers .Where(x => x.ShouldSendMessage(messageType)) .ToArray(); } public ISendingAgent[] FindLocalSubscribers(Type messageType) { return _subscribers .OfType<LocalQueueSettings>() .Where(x => x.ShouldSendMessage(messageType)) .Select(x => x.Agent) .ToArray(); } public ITopicRouter[] FindTopicRoutersForMessageType(Type messageType) { var routers = FindSubscribersForMessageType(messageType).OfType<ITopicRouter>().ToArray(); return routers.Any() ? routers : _subscribers.OfType<ITopicRouter>().ToArray(); } public IEnumerable<Endpoint> AllEndpoints() { return _transports.SelectMany(x => x.Endpoints()); } public Endpoint EndpointFor(Uri uri) { return AllEndpoints().FirstOrDefault(x => x.Uri == uri); } public void Dispose() { foreach (var kv in _senders.Enumerate()) { kv.Value.SafeDispose(); } foreach (var listener in _disposables) { listener.SafeDispose(); } foreach (var transport in _transports.OfType<IDisposable>()) { transport.Dispose(); } } } }
#region MIT License /* * Copyright (c) 2005-2008 by Jonathan Mark Porter. http://physics2d.googlepages.com/ * Edited (2009) by Ian Qvist to be included in Farseer Physics. http://codeplex.com/FarseerPhysics * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Collections.Generic; using System.Runtime.InteropServices; using FarseerGames.FarseerPhysics.Dynamics; using FarseerGames.FarseerPhysics.Interfaces; namespace FarseerGames.FarseerPhysics.Collisions { /// <summary> /// Spartial hashing stores all the geometries that can collide in a list. /// Using this algorithm, you can quickly tell what objects might collide in a certain area. /// </summary> public class SpatialHashCollider : IBroadPhaseCollider { private PhysicsSimulator _physicsSimulator; private Dictionary<long, List<Geom>> _hash; private Dictionary<long, object> _filter; private float _cellSize; private float _cellSizeInv; public bool AutoAdjustCellSize = true; public SpatialHashCollider(PhysicsSimulator physicsSimulator) : this(physicsSimulator, 50, 2048) { _physicsSimulator = physicsSimulator; } public SpatialHashCollider(PhysicsSimulator physicsSimulator, float cellSize, int hashCapacity) { _physicsSimulator = physicsSimulator; _hash = new Dictionary<long, List<Geom>>(hashCapacity); _filter = new Dictionary<long, object>(); _cellSize = cellSize; _cellSizeInv = 1 / cellSize; } #region IBroadPhaseCollider Members /// <summary> /// Fires when a broad phase collision occurs /// </summary> public event BroadPhaseCollisionHandler OnBroadPhaseCollision; ///<summary> /// Not required by collider ///</summary> public void ProcessRemovedGeoms() { } ///<summary> /// Not required by collider ///</summary> public void ProcessDisposedGeoms() { } ///<summary> /// Not required by collider ///</summary> public void Add(Geom geom) { } /// <summary> /// Updates this instance. /// </summary> public void Update() { if (_physicsSimulator.geomList.Count == 0) { return; } //Calculate hash map FillHash(); //Iterate the hash map RunHash(); } #endregion public float CellSize { get { return _cellSize; } set { _cellSize = value; _cellSizeInv = 1 / value; } } private void FillHash() { //Average used to optimize cell size if AutoAdjustCellSize = true. float average = 0; for (int i = 0; i < _physicsSimulator.geomList.Count; i++) { Geom geom = _physicsSimulator.geomList[i]; //Note: Could do some checking here for geometries that should not be included in the hashmap AABB aabb = geom.AABB; if (AutoAdjustCellSize) average += Math.Max(aabb.Max.X - aabb.Min.X, aabb.Max.Y - aabb.Min.Y); int minX = (int)(aabb.Min.X * _cellSizeInv); int maxX = (int)(aabb.Max.X * _cellSizeInv) + 1; int minY = (int)(aabb.Min.Y * _cellSizeInv); int maxY = (int)(aabb.Max.Y * _cellSizeInv) + 1; for (int x = minX; x < maxX; x++) { for (int y = minY; y < maxY; y++) { long key = PairID.GetHash(x, y); List<Geom> list; if (!_hash.TryGetValue(key, out list)) { list = new List<Geom>(); _hash.Add(key, list); } list.Add(geom); } } } if (AutoAdjustCellSize) { CellSize = 2 * average / (_physicsSimulator.geomList.Count); } } private void RunHash() { List<long> keysToRemove = new List<long>(_hash.Count); foreach (KeyValuePair<long, List<Geom>> pair in _hash) { // If there are no geometries in the list. Remove it. // If there are any geometries in the list, process them. List<Geom> list = pair.Value; if (list.Count == 0) { keysToRemove.Add(pair.Key); } else { for (int i = 0; i < list.Count - 1; i++) { Geom geometryA = list[i]; for (int j = i + 1; j < list.Count; j++) { Geom geometryB = list[j]; if (!geometryA.body.Enabled || !geometryB.body.Enabled) continue; if ((geometryA.CollisionGroup == geometryB.CollisionGroup) && geometryA.CollisionGroup != 0 && geometryB.CollisionGroup != 0) continue; if (!geometryA.CollisionEnabled || !geometryB.CollisionEnabled) continue; if (geometryA.body.isStatic && geometryB.body.isStatic) continue; if (geometryA.body == geometryB.body) continue; if (((geometryA.CollisionCategories & geometryB.CollidesWith) == CollisionCategory.None) & ((geometryB.CollisionCategories & geometryA.CollidesWith) == CollisionCategory.None)) continue; if (geometryA.FindDNC(geometryB) || geometryB.FindDNC(geometryA)) { continue; } long key = PairID.GetId(geometryA.id, geometryB.id); if (!_filter.ContainsKey(key)) { _filter.Add(key, null); //Check if there is intersection bool intersection = AABB.Intersect(geometryA.AABB, geometryB.AABB); //User can cancel collision if (OnBroadPhaseCollision != null) intersection = OnBroadPhaseCollision(geometryA, geometryB); if (!intersection) continue; Arbiter arbiter = _physicsSimulator.arbiterPool.Fetch(); arbiter.ConstructArbiter(geometryA, geometryB, _physicsSimulator); if (!_physicsSimulator.arbiterList.Contains(arbiter)) _physicsSimulator.arbiterList.Add(arbiter); else _physicsSimulator.arbiterPool.Insert(arbiter); } } } list.Clear(); } } _filter.Clear(); //Remove all the empty lists from the hash for (int index = 0; index < keysToRemove.Count; ++index) { _hash.Remove(keysToRemove[index]); } } } [StructLayout(LayoutKind.Explicit)] public struct PairID { public static long GetId(int id1, int id2) { PairID result; result.ID = 0; if (id1 > id2) { result.lowID = id2; result.highID = id1; } else { result.lowID = id1; result.highID = id2; } return result.ID; } public static long GetHash(int value1, int value2) { PairID result; result.ID = 0; result.lowID = value1; result.highID = value2; return result.ID; } public static void GetIds(long id, out int id1, out int id2) { PairID result; result.lowID = 0; result.highID = 0; result.ID = id; id1 = result.lowID; id2 = result.highID; } [FieldOffset(0)] long ID; [FieldOffset(0)] int lowID; [FieldOffset(sizeof(int))] int highID; } }
using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Text; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PlantUmlClassDiagramGenerator.Library; using System.Runtime.InteropServices; namespace PlantUmlClassDiagramGenerator { class Program { enum OptionType { Value, Switch } static readonly Dictionary<string, OptionType> options = new Dictionary<string, OptionType>() { ["-dir"] = OptionType.Switch, ["-public"] = OptionType.Switch, ["-ignore"] = OptionType.Value, ["-excludePaths"] = OptionType.Value, ["-createAssociation"] = OptionType.Switch, ["-allInOne"] = OptionType.Switch }; static int Main(string[] args) { Dictionary<string, string> parameters = MakeParameters(args); if (!parameters.ContainsKey("in")) { Console.WriteLine("Specify a source file name or directory name."); return -1; } if (parameters.ContainsKey("-dir")) { if (!GeneratePlantUmlFromDir(parameters)) { return -1; } } else { if (!GeneratePlantUmlFromFile(parameters)) { return -1; } } return 0; } private static bool GeneratePlantUmlFromFile(Dictionary<string, string> parameters) { var inputFileName = parameters["in"]; if (!File.Exists(inputFileName)) { Console.WriteLine($"\"{inputFileName}\" does not exist."); return false; } string outputFileName; if (parameters.ContainsKey("out")) { outputFileName = parameters["out"]; try { var outdir = Path.GetDirectoryName(outputFileName); Directory.CreateDirectory(outdir); } catch (Exception e) { Console.WriteLine(e); return false; } } else { outputFileName = CombinePath(Path.GetDirectoryName(inputFileName), Path.GetFileNameWithoutExtension(inputFileName) + ".puml"); } try { using var stream = new FileStream(inputFileName, FileMode.Open, FileAccess.Read); var tree = CSharpSyntaxTree.ParseText(SourceText.From(stream)); var root = tree.GetRoot(); Accessibilities ignoreAcc = GetIgnoreAccessibilities(parameters); using var filestream = new FileStream(outputFileName, FileMode.Create, FileAccess.Write); using var writer = new StreamWriter(filestream); var gen = new ClassDiagramGenerator(writer, " ", ignoreAcc, parameters.ContainsKey("-createAssociation")); gen.Generate(root); } catch (Exception e) { Console.WriteLine(e); return false; } return true; } private static bool GeneratePlantUmlFromDir(Dictionary<string, string> parameters) { var inputRoot = parameters["in"]; if (!Directory.Exists(inputRoot)) { Console.WriteLine($"Directory \"{inputRoot}\" does not exist."); return false; } // Use GetFullPath to fully support relative paths. var outputRoot = Path.GetFullPath(inputRoot); if (parameters.ContainsKey("out")) { outputRoot = parameters["out"]; try { Directory.CreateDirectory(outputRoot); } catch (Exception e) { Console.WriteLine(e); return false; } } var excludePaths = new List<string>(); var pumlexclude = CombinePath(inputRoot, ".pumlexclude"); if (File.Exists(pumlexclude)) { excludePaths = File.ReadAllLines(pumlexclude).ToList(); } if (parameters.ContainsKey("-excludePaths")) { excludePaths.AddRange(parameters["-excludePaths"].Split(',')); } var files = Directory.EnumerateFiles(inputRoot, "*.cs", SearchOption.AllDirectories); var includeRefs = new StringBuilder(); includeRefs.AppendLine("@startuml"); var error = false; foreach (var inputFile in files) { if (excludePaths .Select(p => CombinePath(inputRoot, p)) .Any(p => inputFile.StartsWith(p, StringComparison.InvariantCultureIgnoreCase))) { Console.WriteLine($"Skipped \"{inputFile}\"..."); continue; } Console.WriteLine($"Processing \"{inputFile}\"..."); try { var outputDir = CombinePath(outputRoot, Path.GetDirectoryName(inputFile).Replace(inputRoot, "")); Directory.CreateDirectory(outputDir); var outputFile = CombinePath(outputDir, Path.GetFileNameWithoutExtension(inputFile) + ".puml"); using (var stream = new FileStream(inputFile, FileMode.Open, FileAccess.Read)) { var tree = CSharpSyntaxTree.ParseText(SourceText.From(stream)); var root = tree.GetRoot(); Accessibilities ignoreAcc = GetIgnoreAccessibilities(parameters); using var filestream = new FileStream(outputFile, FileMode.Create, FileAccess.Write); using var writer = new StreamWriter(filestream); var gen = new ClassDiagramGenerator(writer, " ", ignoreAcc, parameters.ContainsKey("-createAssociation")); gen.Generate(root); } if (parameters.ContainsKey("-allInOne")) { var lines = File.ReadAllLines(outputFile); foreach (string line in lines.Skip(1).SkipLast(1)) { includeRefs.AppendLine(line); } } else { var newRoot = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @".\" : @"."; includeRefs.AppendLine("!include " + outputFile.Replace(outputRoot, newRoot)); } } catch (Exception e) { Console.WriteLine(e); error = true; } } includeRefs.AppendLine("@enduml"); File.WriteAllText(CombinePath(outputRoot, "include.puml"), includeRefs.ToString()); if (error) { Console.WriteLine("There were files that could not be processed."); return false; } return true; } private static Accessibilities GetIgnoreAccessibilities(Dictionary<string, string> parameters) { var ignoreAcc = Accessibilities.None; if (parameters.ContainsKey("-public")) { ignoreAcc = Accessibilities.Private | Accessibilities.Internal | Accessibilities.Protected | Accessibilities.ProtectedInternal; } else if (parameters.ContainsKey("-ignore")) { var ignoreItems = parameters["-ignore"].Split(','); foreach (var item in ignoreItems) { if (Enum.TryParse(item, true, out Accessibilities acc)) { ignoreAcc |= acc; } } } return ignoreAcc; } private static Dictionary<string, string> MakeParameters(string[] args) { var currentKey = ""; var parameters = new Dictionary<string, string>(); foreach (var arg in args) { if (currentKey != string.Empty) { parameters.Add(currentKey, arg); currentKey = ""; continue; } if (options.ContainsKey(arg)) { if (options[arg] == OptionType.Value) { currentKey = arg; } else { parameters.Add(arg, string.Empty); } } else if (!parameters.ContainsKey("in")) { parameters.Add("in", arg); } else if (!parameters.ContainsKey("out")) { parameters.Add("out", arg); } } return parameters; } private static string CombinePath(string first, string second) { return first.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar + second.TrimStart(Path.DirectorySeparatorChar); } } }
/* Originally started back last year, and completely rewritten from the ground up to handle the * Profiles for InWorldz, LLC. * Modified again on 1/22/2011 by Beth Reischl to: * Pull a couple of DB queries from the Classifieds section that were not needed * Pulled a DB query from Profiles and modified another one. * Pulled out the queryParcelUUID from PickInfoUpdate method, this was resulting in null parcel IDs * being passed all the time. * Fixed the PickInfoUpdate and PickInfoRequest to show Username, Parcel Information, Region Name, (xyz) * coords for proper teleportation */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Xml; using OpenMetaverse; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Communications.Cache; using OpenSim.Data.SimpleDB; namespace OpenSimProfile.Modules.OpenProfile { public class OpenProfileModule : IRegionModule { // // Log module // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // // Module vars // private bool m_Enabled = true; private ConnectionFactory _connFactory; private ConnectionFactory _regionConnFactory; public void Initialize(Scene scene, IConfigSource config) { if (!m_Enabled) return; //TODO: At some point, strip this out of the ini file, in Search Module, // we're going to recycle the Profile connection string however to make // life a bit easier. IConfig profileConfig = config.Configs["Startup"]; string connstr = profileConfig.GetString("core_connection_string", String.Empty); m_log.Info("[PROFILE] Profile module is activated"); //TODO: Bad assumption on my part that we're enabling it and the connstr is actually // valid, but I'm sick of dinking with this thing :) m_Enabled = true; _connFactory = new ConnectionFactory("MySQL", connstr); string storageConnStr = profileConfig.GetString("storage_connection_string", String.Empty); _regionConnFactory = new ConnectionFactory("MySQL", storageConnStr); // Hook up events scene.EventManager.OnNewClient += OnNewClient; } public void PostInitialize() { if (!m_Enabled) return; } public void Close() { } public string Name { get { return "ProfileModule"; } } public bool IsSharedModule { get { return true; } } /// New Client Event Handler private void OnNewClient(IClientAPI client) { // Classifieds client.AddGenericPacketHandler("avatarclassifiedsrequest", HandleAvatarClassifiedsRequest); client.OnClassifiedInfoUpdate += ClassifiedInfoUpdate; client.OnClassifiedDelete += ClassifiedDelete; // Picks //TODO: there is an error generated here in the Grid as we've removed the // need for this and wrapped it down below. This needs to be fixed. // This applies to any reqeusts made for general info. //client.AddGenericPacketHandler("avatarpicksrequest", HandlePickInfoRequest); client.AddGenericPacketHandler("pickinforequest", HandlePickInfoRequest); client.OnPickInfoUpdate += PickInfoUpdate; client.OnPickDelete += PickDelete; // Notes client.AddGenericPacketHandler("avatarnotesrequest", HandleAvatarNotesRequest); client.OnAvatarNotesUpdate += AvatarNotesUpdate; // Interests client.OnRequestAvatarProperties += new RequestAvatarProperties(client_OnRequestAvatarProperties); client.OnAvatarInterestsUpdate += AvatarInterestsUpdate; } void client_OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID) { List<String> alist = new List<String>(); alist.Add(avatarID.ToString()); HandleAvatarInterestsRequest(remoteClient, alist); HandleAvatarPicksRequest(remoteClient, alist); } // Interests Handler public void HandleAvatarInterestsRequest(Object sender, List<String> args) { IClientAPI remoteClient = (IClientAPI)sender; UUID avatarID = new UUID(args[0]); using (ISimpleDB db = _connFactory.GetConnection()) { uint skillsMask = new uint(); string skillsText = String.Empty; uint wantToMask = new uint(); string wantToText = String.Empty; string languagesText = String.Empty; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); string query = "SELECT skillsMask, skillsText, wantToMask, wantToText, languagesText FROM users " + "WHERE UUID=?avatarID"; List<Dictionary<string, string>> results = db.QueryWithResults(query, parms); foreach (Dictionary<string, string> row in results) { skillsMask = Convert.ToUInt16(row["skillsMask"]); skillsText = row["skillsText"]; wantToMask = Convert.ToUInt16(row["wantToMask"]); wantToText = row["wantToText"]; languagesText = row["languagesText"]; } remoteClient.SendAvatarInterestsReply(avatarID, wantToMask, wantToText, skillsMask, skillsText, languagesText); } } // Interests Update public void AvatarInterestsUpdate(IClientAPI remoteClient, uint querySkillsMask, string querySkillsText, uint queryWantToMask, string queryWantToText, string queryLanguagesText) { UUID avatarID = remoteClient.AgentId; using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); parms.Add("?skillsMask", querySkillsMask); parms.Add("?skillsText", querySkillsText); parms.Add("?wantToMask", queryWantToMask); parms.Add("?wantToText", queryWantToText); parms.Add("?languagesText", queryLanguagesText); string query = "UPDATE users set skillsMask=?wantToMask, skillsText=?wantToText, wantToMask=?skillsMask, " + "wantToText=?skillsText, languagesText=?languagesText where UUID=?avatarID"; db.QueryNoResults(query, parms); } } // Classifieds Handler public void HandleAvatarClassifiedsRequest(Object sender, string method, List<String> args) { if (!(sender is IClientAPI)) return; IClientAPI remoteClient = (IClientAPI)sender; UUID avatarID = new UUID(args[0]); using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<UUID, string> classifieds = new Dictionary<UUID, string>(); Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); string query = "SELECT classifieduuid, name from classifieds " + "WHERE creatoruuid=?avatarID"; List<Dictionary<string, string>> results = db.QueryWithResults(query, parms); foreach (Dictionary<string, string> row in results) { classifieds[new UUID(row["classifieduuid"].ToString())] = row["name"].ToString(); } remoteClient.SendAvatarClassifiedReply(avatarID, classifieds); } } // Classifieds Update public const int MIN_CLASSIFIED_PRICE = 50; public void ClassifiedInfoUpdate(UUID queryclassifiedID, uint queryCategory, string queryName, string queryDescription, UUID queryParcelID, uint queryParentEstate, UUID querySnapshotID, Vector3 queryGlobalPos, byte queryclassifiedFlags, int queryclassifiedPrice, IClientAPI remoteClient) { // getting information lined up for the query UUID avatarID = remoteClient.AgentId; UUID regionUUID = remoteClient.Scene.RegionInfo.RegionID; UUID ParcelID = UUID.Zero; uint regionX = remoteClient.Scene.RegionInfo.RegionLocX; uint regionY = remoteClient.Scene.RegionInfo.RegionLocY; // m_log.DebugFormat("[CLASSIFIED]: Got the RegionX Location as: {0}, and RegionY as: {1}", regionX.ToString(), regionY.ToString()); string regionName = remoteClient.Scene.RegionInfo.RegionName; int creationDate = Util.UnixTimeSinceEpoch(); int expirationDate = creationDate + 604800; if (queryclassifiedPrice < MIN_CLASSIFIED_PRICE) { m_log.ErrorFormat("[CLASSIFIED]: Got a request for invalid price I'z${0} on a classified from {1}.", queryclassifiedPrice.ToString(), remoteClient.AgentId.ToString()); remoteClient.SendAgentAlertMessage("Error: The minimum price for a classified advertisement is I'z$" + MIN_CLASSIFIED_PRICE.ToString()+".", true); return; } // Check for hacked names that start with special characters if (!Char.IsLetterOrDigit(queryName, 0)) { m_log.ErrorFormat("[CLASSIFIED]: Got a hacked request from {0} for invalid name classified name: {1}", remoteClient.AgentId.ToString(), queryName); remoteClient.SendAgentAlertMessage("Error: The name of your classified must start with a letter or a number. No punctuation is allowed.", true); return; } // In case of insert, original values are the new values (by default) int origPrice = 0; using (ISimpleDB db = _connFactory.GetConnection()) { //if this is an existing classified make sure the client is the owner or don't touch it string existingCheck = "SELECT creatoruuid FROM classifieds WHERE classifieduuid = ?classifiedID"; Dictionary<string, object> checkParms = new Dictionary<string, object>(); checkParms.Add("?classifiedID", queryclassifiedID); List<Dictionary<string, string>> existingResults = db.QueryWithResults(existingCheck, checkParms); if (existingResults.Count > 0) { string existingAuthor = existingResults[0]["creatoruuid"]; if (existingAuthor != avatarID.ToString()) { m_log.ErrorFormat("[CLASSIFIED]: Got a request for from {0} to modify a classified from {1}: {2}", remoteClient.AgentId.ToString(), existingAuthor, queryclassifiedID.ToString()); remoteClient.SendAgentAlertMessage("Error: You do not have permission to modify that classified ad.", true); return; } } Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); parms.Add("?classifiedID", queryclassifiedID); parms.Add("?category", queryCategory); parms.Add("?name", queryName); parms.Add("?description", queryDescription); //parms.Add("?parcelID", queryParcelID); parms.Add("?parentEstate", queryParentEstate); parms.Add("?snapshotID", querySnapshotID); parms.Add("?globalPos", queryGlobalPos); parms.Add("?classifiedFlags", queryclassifiedFlags); parms.Add("?classifiedPrice", queryclassifiedPrice); parms.Add("?creationDate", creationDate); parms.Add("?expirationDate", expirationDate); parms.Add("?regionUUID", regionUUID); parms.Add("?regionName", regionName); // We need parcelUUID from land to place in the query properly // However, there can be multiple Parcel UUIDS per region, // so we need to do some math from the classified entry // to the positioning of the avatar // The point we have is a global position value, which means // we need to to get the location with: (GlobalX / 256) - RegionX and // (GlobalY / 256) - RegionY for the values of the avatar standign position // then compare that to the parcels for the closest match // explode the GlobalPos value off the bat string origGlobPos = queryGlobalPos.ToString(); string tempAGlobPos = origGlobPos.Replace("<", String.Empty); string tempBGlobPos = tempAGlobPos.Replace(">", String.Empty); char[] delimiterChars = { ',', ' ' }; string[] globalPosBits = tempBGlobPos.Split(delimiterChars); uint tempAvaXLoc = Convert.ToUInt32(Convert.ToDouble(globalPosBits[0])); uint tempAvaYLoc = Convert.ToUInt32(Convert.ToDouble(globalPosBits[2])); uint avaXLoc = tempAvaXLoc - (256 * regionX); uint avaYLoc = tempAvaYLoc - (256 * regionY); //uint avatarPosX = (posGlobalX / 256) - regionX; parms.Add("?avaXLoc", avaXLoc.ToString()); parms.Add("?avaYLoc", avaYLoc.ToString()); string parcelLocate = "select uuid, MIN(ABS(UserLocationX - ?avaXLoc)) as minXValue, MIN(ABS(UserLocationY - ?avaYLoc)) as minYValue from land where RegionUUID=?regionUUID GROUP BY UserLocationX ORDER BY minXValue, minYValue LIMIT 1;"; using (ISimpleDB landDb = _regionConnFactory.GetConnection()) { List<Dictionary<string, string>> parcelLocated = landDb.QueryWithResults(parcelLocate, parms); foreach (Dictionary<string, string> row in parcelLocated) { ParcelID = new UUID(row["uuid"].ToString()); } } parms.Add("?parcelID", ParcelID); string queryClassifieds = "select * from classifieds where classifieduuid=?classifiedID AND creatoruuid=?avatarID"; List<Dictionary <string, string>> results = db.QueryWithResults(queryClassifieds, parms); bool isUpdate = false; int costToApply; string transactionDesc; if (results.Count != 0) { if (results.Count != 1) { remoteClient.SendAgentAlertMessage("Classified record is not consistent. Contact Support for assistance.", false); m_log.ErrorFormat("[CLASSIFIED]: Error, query for user {0} classified ad {1} returned {2} results.", avatarID.ToString(), queryclassifiedID.ToString(), results.Count.ToString()); return; } // This is an upgrade of a classified ad. Dictionary<string, string> row = results[0]; isUpdate = true; transactionDesc = "Classified price change"; origPrice = Convert.ToInt32(row["priceforlisting"]); // Also preserve original creation date and expiry. creationDate = Convert.ToInt32(row["creationdate"]); expirationDate = Convert.ToInt32(row["expirationdate"]); costToApply = queryclassifiedPrice - origPrice; if (costToApply < 0) costToApply = 0; } else { // This is the initial placement of the classified. transactionDesc = "Classified charge"; creationDate = Util.UnixTimeSinceEpoch(); expirationDate = creationDate + 604800; costToApply = queryclassifiedPrice; } EventManager.ClassifiedPaymentArgs paymentArgs = new EventManager.ClassifiedPaymentArgs(remoteClient.AgentId, queryclassifiedID, origPrice, queryclassifiedPrice, transactionDesc, true); if (costToApply > 0) { // Now check whether the payment is authorized by the currency system. ((Scene)remoteClient.Scene).EventManager.TriggerClassifiedPayment(remoteClient, paymentArgs); if (!paymentArgs.mIsAuthorized) return; // already reported to user by the check above. } string query; if (isUpdate) { query = "UPDATE classifieds set creationdate=?creationDate, " + "category=?category, name=?name, description=?description, parceluuid=?parcelID, " + "parentestate=?parentEstate, snapshotuuid=?snapshotID, simname=?regionName, posglobal=?globalPos, parcelname=?name, " + " classifiedflags=?classifiedFlags, priceforlisting=?classifiedPrice where classifieduuid=?classifiedID"; } else { query = "INSERT into classifieds (classifieduuid, creatoruuid, creationdate, expirationdate, category, name, " + "description, parceluuid, parentestate, snapshotuuid, simname, posglobal, parcelname, classifiedflags, priceforlisting) " + "VALUES (?classifiedID, ?avatarID, ?creationDate, ?expirationDate, ?category, ?name, ?description, ?parcelID, " + "?parentEstate, ?snapshotID, ?regionName, ?globalPos, ?name, ?classifiedFlags, ?classifiedPrice)"; } db.QueryNoResults(query, parms); if (costToApply > 0) // no refunds for lower prices { // Handle the actual money transaction here. paymentArgs.mIsPreCheck = false; // now call it again but for real this time ((Scene)remoteClient.Scene).EventManager.TriggerClassifiedPayment(remoteClient, paymentArgs); // Errors reported by the payment request above. } } } // Classifieds Delete public void ClassifiedDelete(UUID queryClassifiedID, IClientAPI remoteClient) { UUID avatarID = remoteClient.AgentId; UUID classifiedID = queryClassifiedID; using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?classifiedID", classifiedID); parms.Add("?avatarID", avatarID); string query = "delete from classifieds where classifieduuid=?classifiedID AND creatorUUID=?avatarID"; db.QueryNoResults(query, parms); } } // Picks Handler public void HandleAvatarPicksRequest(Object sender, List<String> args) { if (!(sender is IClientAPI)) return; IClientAPI remoteClient = (IClientAPI)sender; UUID avatarID = new UUID(args[0]); using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<UUID, string> picksRequest = new Dictionary<UUID, string>(); Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); string query = "SELECT pickuuid, name from userpicks " + "WHERE creatoruuid=?avatarID"; List<Dictionary<string, string>> results = db.QueryWithResults(query, parms); foreach (Dictionary<string, string> row in results) { picksRequest[new UUID(row["pickuuid"].ToString())] = row["name"].ToString(); } remoteClient.SendAvatarPicksReply(avatarID, picksRequest); } } // Picks Request public void HandlePickInfoRequest(Object sender, string method, List<String> args) { if (!(sender is IClientAPI)) return; IClientAPI remoteClient = (IClientAPI)sender; UUID avatarID = new UUID(args[0]); UUID pickID = new UUID(args[1]); using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); parms.Add("?pickID", pickID); string query = "SELECT * from userpicks WHERE creatoruuid=?avatarID AND pickuuid=?pickID"; List<Dictionary<string, string>> results = db.QueryWithResults(query, parms); bool topPick = new bool(); UUID parcelUUID = new UUID(); string name = String.Empty; string description = String.Empty; UUID snapshotID = new UUID(); string userName = String.Empty; string originalName = String.Empty; string simName = String.Empty; Vector3 globalPos = new Vector3(); int sortOrder = new int(); bool enabled = new bool(); foreach (Dictionary<string, string> row in results) { topPick = Boolean.Parse(row["toppick"]); parcelUUID = UUID.Parse(row["parceluuid"]); name = row["name"]; description = row["description"]; snapshotID = UUID.Parse(row["snapshotuuid"]); userName = row["user"]; //userName = row["simname"]; originalName = row["originalname"]; simName = row["simname"]; globalPos = Vector3.Parse(row["posglobal"]); sortOrder = Convert.ToInt32(row["sortorder"]); enabled = Boolean.Parse(row["enabled"]); } remoteClient.SendPickInfoReply( pickID, avatarID, topPick, parcelUUID, name, description, snapshotID, userName, originalName, simName, globalPos, sortOrder, enabled); } } // Picks Update // pulled the original method due to UUID queryParcelID always being returned as null. If this is ever fixed to where // the viewer does in fact return the parcelID, then we can put this back in. //public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, // UUID queryParcelID, Vector3 queryGlobalPos, UUID snapshotID, int sortOrder, bool enabled) public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, Vector3 queryGlobalPos, UUID snapshotID, int sortOrder, bool enabled) { string userRegion = remoteClient.Scene.RegionInfo.RegionName; UUID userRegionID = remoteClient.Scene.RegionInfo.RegionID; string userFName = remoteClient.FirstName; string userLName = remoteClient.LastName; string avatarName = userFName + " " + userLName; UUID tempParcelUUID = UUID.Zero; UUID avatarID = remoteClient.AgentId; using (ISimpleDB db = _connFactory.GetConnection()) { //if this is an existing pick make sure the client is the owner or don't touch it string existingCheck = "SELECT creatoruuid FROM userpicks WHERE pickuuid = ?pickID"; Dictionary<string, object> checkParms = new Dictionary<string, object>(); checkParms.Add("?pickID", pickID); List<Dictionary<string, string>> existingResults = db.QueryWithResults(existingCheck, checkParms); if (existingResults.Count > 0) { if (existingResults[0]["creatoruuid"] != avatarID.ToString()) { return; } } //reassign creator id, it has to be this avatar creatorID = avatarID; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); parms.Add("?pickID", pickID); parms.Add("?creatorID", creatorID); parms.Add("?topPick", topPick); parms.Add("?name", name); parms.Add("?desc", desc); parms.Add("?globalPos", queryGlobalPos); parms.Add("?snapshotID", snapshotID); parms.Add("?sortOrder", sortOrder); parms.Add("?enabled", enabled); parms.Add("?regionID", userRegionID); parms.Add("?regionName", userRegion); // we need to know if we're on a parcel or not, and if so, put it's UUID in there // viewer isn't giving it to us from what I can determine // TODO: David will need to clean this up cause more arrays are not my thing :) string queryParcelUUID = "select UUID from land where regionUUID=?regionID AND name=?name limit 1"; using (ISimpleDB landDb = _regionConnFactory.GetConnection()) { List<Dictionary<string, string>> simID = landDb.QueryWithResults(queryParcelUUID, parms); foreach (Dictionary<string, string> row in simID) { tempParcelUUID = UUID.Parse(row["UUID"]); } } UUID parcelUUID = tempParcelUUID; parms.Add("?parcelID", parcelUUID); m_log.Debug("Got parcel of: " + parcelUUID.ToString()); parms.Add("?parcelName", name); string queryPicksCount = "select COUNT(pickuuid) from userpicks where pickuuid=?pickID AND " + "creatoruuid=?creatorID"; List<Dictionary <string, string>> countList = db.QueryWithResults(queryPicksCount, parms); string query; string picksCount = String.Empty; foreach (Dictionary<string, string> row in countList) { picksCount = row["COUNT(pickuuid)"]; } parms.Add("?avatarName", avatarName); //TODO: We're defaulting topPick to false for the moment along with enabled default to True // We'll need to look over the conversion vs MySQL cause data truncating should not happen if(picksCount == "0") { query = "INSERT into userpicks (pickuuid, creatoruuid, toppick, parceluuid, name, description, snapshotuuid, user, " + "originalname, simname, posglobal, sortorder, enabled) " + "VALUES (?pickID, ?creatorID, 'false', ?parcelID, ?name, ?desc, ?snapshotID, " + "?avatarName, ?parcelName, ?regionName, ?globalPos, ?sortOrder, 'true')"; } else { query = "UPDATE userpicks set toppick='false', " + " parceluuid=?parcelID, name=?name, description=?desc, snapshotuuid=?snapshotID, " + "user=?avatarName, originalname=?parcelName, simname=?regionName, posglobal=?globalPos, sortorder=?sortOrder, " + " enabled='true' where pickuuid=?pickID"; } db.QueryNoResults(query, parms); } } // Picks Delete public void PickDelete(IClientAPI remoteClient, UUID queryPickID) { UUID avatarID = remoteClient.AgentId; using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?pickID", queryPickID); parms.Add("?avatarID", avatarID); string query = "delete from userpicks where pickuuid=?pickID AND creatoruuid=?avatarID"; db.QueryNoResults(query, parms); } } private const string LEGACY_EMPTY = "No notes currently for this avatar!"; public void HandleAvatarNotesRequest(Object sender, string method, List<String> args) { if (!(sender is IClientAPI)) return; IClientAPI remoteClient = (IClientAPI)sender; UUID avatarID = remoteClient.AgentId; UUID targetAvatarID = new UUID(args[0]); using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); parms.Add("?targetID", targetAvatarID); string query = "SELECT notes from usernotes where useruuid=?avatarID AND targetuuid=?targetID"; List<Dictionary<string, string>> notesResult = db.QueryWithResults(query, parms); string notes = String.Empty; if (notesResult.Count > 0) notes = notesResult[0]["notes"]; if (notes == LEGACY_EMPTY) // filter out the old text that said there was no text. ;) notes = String.Empty; remoteClient.SendAvatarNotesReply(targetAvatarID, notes); } } public void AvatarNotesUpdate(IClientAPI remoteClient, UUID queryTargetID, string queryNotes) { UUID avatarID = remoteClient.AgentId; // allow leading spaces for formatting, but TrimEnd will help us detect an empty field other than spaces string notes = queryNotes.TrimEnd(); // filter out the old text that said there was no text. ;) if (notes == LEGACY_EMPTY) notes = String.Empty; using (ISimpleDB db = _connFactory.GetConnection()) { Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); parms.Add("?targetID", queryTargetID); parms.Add("?notes", notes); string query; if (String.IsNullOrEmpty(notes)) query = "DELETE FROM usernotes WHERE useruuid=?avatarID AND targetuuid=?targetID"; else query = "INSERT INTO usernotes(useruuid, targetuuid, notes) VALUES(?avatarID,?targetID,?notes) ON DUPLICATE KEY UPDATE notes=?notes"; db.QueryNoResults(query, parms); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Linq.Parallel.Tests { public class SkipSkipWhileTests { // // Skip // public static IEnumerable<object[]> SkipUnorderedData(int[] counts) { Func<int, IEnumerable<int>> skip = x => new[] { -x, -1, 0, 1, x / 2, x, x * 2 }.Distinct(); foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), skip)) yield return results; } public static IEnumerable<object[]> SkipData(int[] counts) { Func<int, IEnumerable<int>> skip = x => new[] { -x, -1, 0, 1, x / 2, x, x * 2 }.Distinct(); foreach (object[] results in Sources.Ranges(counts.Cast<int>(), skip)) yield return results; } [Theory] [MemberData(nameof(SkipUnorderedData), new[] { 0, 1, 2, 16 })] public static void Skip_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements are skipped isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip))); foreach (int i in query.Skip(skip)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SkipUnorderedData), new[] { 1024 * 32 })] public static void Skip_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { Skip_Unordered(labeled, count, skip); } [Theory] [MemberData(nameof(SkipData), new[] { 0, 1, 2, 16 })] public static void Skip(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = Math.Max(0, skip); foreach (int i in query.Skip(skip)) { Assert.Equal(seen++, i); } Assert.Equal(Math.Max(skip, count), seen); } [Theory] [OuterLoop] [MemberData(nameof(SkipData), new[] { 1024 * 32 })] public static void Skip_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { Skip(labeled, count, skip); } [Theory] [MemberData(nameof(SkipUnorderedData), new[] { 0, 1, 2, 16 })] public static void Skip_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements are skipped isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip))); Assert.All(query.Skip(skip).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SkipUnorderedData), new[] { 1024 * 32 })] public static void Skip_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { Skip_Unordered_NotPipelined(labeled, count, skip); } [Theory] [MemberData(nameof(SkipData), new[] { 0, 1, 2, 16 })] public static void Skip_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = Math.Max(0, skip); Assert.All(query.Skip(skip).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(Math.Max(skip, count), seen); } [Theory] [OuterLoop] [MemberData(nameof(SkipData), new[] { 1024 * 32 })] public static void Skip_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { Skip_NotPipelined(labeled, count, skip); } [Fact] public static void Skip_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Skip(0)); } // // SkipWhile // public static IEnumerable<object[]> SkipWhileData(int[] counts) { foreach (object[] results in Sources.Ranges(counts.Cast<int>())) { yield return new[] { results[0], results[1], new[] { 0 } }; yield return new[] { results[0], results[1], Enumerable.Range((int)results[1] / 2, ((int)results[1] - 1) / 2 + 1) }; yield return new[] { results[0], results[1], new[] { (int)results[1] - 1 } }; } } [Theory] [MemberData(nameof(SkipUnorderedData), new[] { 0, 1, 2, 16 })] public static void SkipWhile_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip))); foreach (int i in query.SkipWhile(x => x < skip)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SkipUnorderedData), new[] { 1024 * 32 })] public static void SkipWhile_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_Unordered(labeled, count, skip); } [Theory] [MemberData(nameof(SkipData), new[] { 0, 1, 2, 16 })] public static void SkipWhile(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = Math.Max(0, skip); foreach (int i in query.SkipWhile(x => x < skip)) { Assert.Equal(seen++, i); } Assert.Equal(Math.Max(skip, count), seen); } [Theory] [OuterLoop] [MemberData(nameof(SkipData), new[] { 1024 * 32 })] public static void SkipWhile_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile(labeled, count, skip); } [Theory] [MemberData(nameof(SkipUnorderedData), new[] { 0, 1, 2, 16 })] public static void SkipWhile_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip))); Assert.All(query.SkipWhile(x => x < skip).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SkipUnorderedData), new[] { 1024 * 32 })] public static void SkipWhile_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_Unordered_NotPipelined(labeled, count, skip); } [Theory] [MemberData(nameof(SkipData), new[] { 0, 1, 2, 16 })] public static void SkipWhile_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = Math.Max(0, skip); Assert.All(query.SkipWhile(x => x < skip).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(Math.Max(skip, count), seen); } [Theory] [OuterLoop] [MemberData(nameof(SkipData), new[] { 1024 * 32 })] public static void SkipWhile_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_NotPipelined(labeled, count, skip); } [Theory] [MemberData(nameof(SkipUnorderedData), new[] { 0, 1, 2, 16 })] public static void SkipWhile_Indexed_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip))); foreach (int i in query.SkipWhile((x, index) => index < skip)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SkipUnorderedData), new[] { 1024 * 32 })] public static void SkipWhile_Indexed_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_Indexed_Unordered(labeled, count, skip); } [Theory] [MemberData(nameof(SkipData), new[] { 0, 1, 2, 16 })] public static void SkipWhile_Indexed(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = Math.Max(0, skip); foreach (int i in query.SkipWhile((x, index) => index < skip)) { Assert.Equal(seen++, i); } Assert.Equal(Math.Max(skip, count), seen); } [Theory] [OuterLoop] [MemberData(nameof(SkipData), new[] { 1024 * 32 })] public static void SkipWhile_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_Indexed(labeled, count, skip); } [Theory] [MemberData(nameof(SkipUnorderedData), new[] { 0, 1, 2, 16 })] public static void SkipWhile_Indexed_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip))); Assert.All(query.SkipWhile((x, index) => index < skip), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SkipUnorderedData), new[] { 1024 * 32 })] public static void SkipWhile_Indexed_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_Indexed_Unordered_NotPipelined(labeled, count, skip); } [Theory] [MemberData(nameof(SkipData), new[] { 0, 1, 2, 16 })] public static void SkipWhile_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = Math.Max(0, skip); Assert.All(query.SkipWhile((x, index) => index < skip), x => Assert.Equal(seen++, x)); Assert.Equal(Math.Max(skip, count), seen); } [Theory] [OuterLoop] [MemberData(nameof(SkipData), new[] { 1024 * 32 })] public static void SkipWhile_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_Indexed_NotPipelined(labeled, count, skip); } [Theory] [MemberData(nameof(SkipData), new[] { 0, 1, 2, 16 })] public static void SkipWhile_AllFalse(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.SkipWhile(x => false), x => Assert.Equal(seen++, x)); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(SkipData), new[] { 1024 * 32 })] public static void SkipWhile_AllFalse_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_AllFalse(labeled, count, skip); } [Theory] [MemberData(nameof(SkipData), new[] { 0, 1, 2, 16 })] public static void SkipWhile_AllTrue(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.Empty(query.SkipWhile(x => seen.Add(x))); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SkipData), new[] { 1024 * 32 })] public static void SkipWhile_AllTrue_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_AllTrue(labeled, count, skip); } [Theory] [MemberData(nameof(SkipWhileData), new[] { 2, 16 })] public static void SkipWhile_SomeTrue(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip) { ParallelQuery<int> query = labeled.Item; int seen = skip.Min() == 0 ? 1 : 0; Assert.All(query.SkipWhile(x => skip.Contains(x)), x => Assert.Equal(seen++, x)); Assert.Equal(skip.Min() >= count ? 0 : count, seen); } [Theory] [OuterLoop] [MemberData(nameof(SkipWhileData), new[] { 1024 * 32 })] public static void SkipWhile_SomeTrue_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip) { SkipWhile_SomeTrue(labeled, count, skip); } [Theory] [MemberData(nameof(SkipWhileData), new[] { 2, 16 })] public static void SkipWhile_SomeFalse(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip) { ParallelQuery<int> query = labeled.Item; int seen = skip.Min(); Assert.All(query.SkipWhile(x => !skip.Contains(x)), x => Assert.Equal(seen++, x)); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(SkipWhileData), new[] { 1024 * 32 })] public static void SkipWhile_SomeFalse_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip) { SkipWhile_SomeFalse(labeled, count, skip); } [Fact] public static void SkipWhile_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).SkipWhile(x => true)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SkipWhile((Func<bool, bool>)null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SkipWhile((Func<bool, int, bool>)null)); } } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // // The author gratefully acknowledges the support of David Turner, // Robert Wilhelm, and Werner Lemberg - the authors of the FreeType // library - in producing this work. See http://www.freetype.org for details. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- // // Adaptation for 32-bit screen coordinates has been sponsored by // Liberty Technology Systems, Inc., visit http://lib-sys.com // // Liberty Technology Systems, Inc. is the provider of // PostScript and PDF technology for software developers. // //---------------------------------------------------------------------------- using poly_subpixel_scale_e = MatterHackers.Agg.agg_basics.poly_subpixel_scale_e; namespace MatterHackers.Agg { //-----------------------------------------------------------------cell_aa // A pixel cell. There are no constructors defined and it was done // intentionally in order to avoid extra overhead when allocating an // array of cells. public struct cell_aa { public int x; public int y; public int cover; public int area; public int left, right; public void initial() { x = 0x7FFFFFFF; y = 0x7FFFFFFF; cover = 0; area = 0; left = -1; right = -1; } public void Set(cell_aa cellB) { x = cellB.x; y = cellB.y; cover = cellB.cover; area = cellB.area; left = cellB.left; right = cellB.right; } public void style(cell_aa cellB) { left = cellB.left; right = cellB.right; } public bool not_equal(int ex, int ey, cell_aa cell) { unchecked { return ((ex - x) | (ey - y) | (left - cell.left) | (right - cell.right)) != 0; } } }; //-----------------------------------------------------rasterizer_cells_aa // An internal class that implements the main rasterization algorithm. // Used in the rasterizer. Should not be used directly. public sealed class rasterizer_cells_aa { private int m_num_used_cells; private VectorPOD<cell_aa> m_cells; private VectorPOD<cell_aa> m_sorted_cells; private VectorPOD<sorted_y> m_sorted_y; private QuickSort_cell_aa m_QSorter; private cell_aa m_curr_cell; private cell_aa m_style_cell; private int m_min_x; private int m_min_y; private int m_max_x; private int m_max_y; private bool m_sorted; private enum cell_block_scale_e { cell_block_shift = 12, cell_block_size = 1 << cell_block_shift, cell_block_mask = cell_block_size - 1, cell_block_pool = 256, cell_block_limit = 1024 * cell_block_size }; private struct sorted_y { internal int start; internal int num; }; public rasterizer_cells_aa() { m_QSorter = new QuickSort_cell_aa(); m_sorted_cells = new VectorPOD<cell_aa>(); m_sorted_y = new VectorPOD<sorted_y>(); m_min_x = (0x7FFFFFFF); m_min_y = (0x7FFFFFFF); m_max_x = (-0x7FFFFFFF); m_max_y = (-0x7FFFFFFF); m_sorted = (false); m_style_cell.initial(); m_curr_cell.initial(); } public void reset() { m_num_used_cells = 0; m_curr_cell.initial(); m_style_cell.initial(); m_sorted = false; m_min_x = 0x7FFFFFFF; m_min_y = 0x7FFFFFFF; m_max_x = -0x7FFFFFFF; m_max_y = -0x7FFFFFFF; } public void style(cell_aa style_cell) { m_style_cell.style(style_cell); } private enum dx_limit_e { dx_limit = 16384 << agg_basics.poly_subpixel_scale_e.poly_subpixel_shift }; public void line(int x1, int y1, int x2, int y2) { int poly_subpixel_shift = (int)agg_basics.poly_subpixel_scale_e.poly_subpixel_shift; int poly_subpixel_mask = (int)agg_basics.poly_subpixel_scale_e.poly_subpixel_mask; int poly_subpixel_scale = (int)agg_basics.poly_subpixel_scale_e.poly_subpixel_scale; int dx = x2 - x1; if (dx >= (int)dx_limit_e.dx_limit || dx <= -(int)dx_limit_e.dx_limit) { int cx = (x1 + x2) >> 1; int cy = (y1 + y2) >> 1; line(x1, y1, cx, cy); line(cx, cy, x2, y2); } int dy = y2 - y1; int ex1 = x1 >> poly_subpixel_shift; int ex2 = x2 >> poly_subpixel_shift; int ey1 = y1 >> poly_subpixel_shift; int ey2 = y2 >> poly_subpixel_shift; int fy1 = y1 & poly_subpixel_mask; int fy2 = y2 & poly_subpixel_mask; int x_from, x_to; int p, rem, mod, lift, delta, first, incr; if (ex1 < m_min_x) m_min_x = ex1; if (ex1 > m_max_x) m_max_x = ex1; if (ey1 < m_min_y) m_min_y = ey1; if (ey1 > m_max_y) m_max_y = ey1; if (ex2 < m_min_x) m_min_x = ex2; if (ex2 > m_max_x) m_max_x = ex2; if (ey2 < m_min_y) m_min_y = ey2; if (ey2 > m_max_y) m_max_y = ey2; set_curr_cell(ex1, ey1); //everything is on a single horizontal line if (ey1 == ey2) { render_hline(ey1, x1, fy1, x2, fy2); return; } //Vertical line - we have to calculate start and end cells, //and then - the common values of the area and coverage for //all cells of the line. We know exactly there's only one //cell, so, we don't have to call render_hline(). incr = 1; if (dx == 0) { int ex = x1 >> poly_subpixel_shift; int two_fx = (x1 - (ex << poly_subpixel_shift)) << 1; int area; first = poly_subpixel_scale; if (dy < 0) { first = 0; incr = -1; } x_from = x1; delta = first - fy1; m_curr_cell.cover += delta; m_curr_cell.area += two_fx * delta; ey1 += incr; set_curr_cell(ex, ey1); delta = first + first - poly_subpixel_scale; area = two_fx * delta; while (ey1 != ey2) { m_curr_cell.cover = delta; m_curr_cell.area = area; ey1 += incr; set_curr_cell(ex, ey1); } delta = fy2 - poly_subpixel_scale + first; m_curr_cell.cover += delta; m_curr_cell.area += two_fx * delta; return; } //ok, we have to render several hlines p = (poly_subpixel_scale - fy1) * dx; first = poly_subpixel_scale; if (dy < 0) { p = fy1 * dx; first = 0; incr = -1; dy = -dy; } delta = p / dy; mod = p % dy; if (mod < 0) { delta--; mod += dy; } x_from = x1 + delta; render_hline(ey1, x1, fy1, x_from, first); ey1 += incr; set_curr_cell(x_from >> poly_subpixel_shift, ey1); if (ey1 != ey2) { p = poly_subpixel_scale * dx; lift = p / dy; rem = p % dy; if (rem < 0) { lift--; rem += dy; } mod -= dy; while (ey1 != ey2) { delta = lift; mod += rem; if (mod >= 0) { mod -= dy; delta++; } x_to = x_from + delta; render_hline(ey1, x_from, poly_subpixel_scale - first, x_to, first); x_from = x_to; ey1 += incr; set_curr_cell(x_from >> poly_subpixel_shift, ey1); } } render_hline(ey1, x_from, poly_subpixel_scale - first, x2, fy2); } public int min_x() { return m_min_x; } public int min_y() { return m_min_y; } public int max_x() { return m_max_x; } public int max_y() { return m_max_y; } public void sort_cells() { if (m_sorted) return; //Perform sort only the first time. add_curr_cell(); m_curr_cell.x = 0x7FFFFFFF; m_curr_cell.y = 0x7FFFFFFF; m_curr_cell.cover = 0; m_curr_cell.area = 0; if (m_num_used_cells == 0) return; // Allocate the array of cell pointers m_sorted_cells.Allocate(m_num_used_cells); // Allocate and zero the Y array m_sorted_y.Allocate((int)(m_max_y - m_min_y + 1)); m_sorted_y.zero(); cell_aa[] cells = m_cells.Array; sorted_y[] sortedYData = m_sorted_y.Array; cell_aa[] sortedCellsData = m_sorted_cells.Array; // Create the Y-histogram (count the numbers of cells for each Y) for (int i = 0; i < m_num_used_cells; i++) { int Index = cells[i].y - m_min_y; sortedYData[Index].start++; } // Convert the Y-histogram into the array of starting indexes int start = 0; int SortedYSize = m_sorted_y.size(); for (int i = 0; i < SortedYSize; i++) { int v = sortedYData[i].start; sortedYData[i].start = start; start += v; } // Fill the cell pointer array sorted by Y for (int i = 0; i < m_num_used_cells; i++) { int SortedIndex = cells[i].y - m_min_y; int curr_y_start = sortedYData[SortedIndex].start; int curr_y_num = sortedYData[SortedIndex].num; sortedCellsData[curr_y_start + curr_y_num] = cells[i]; ++sortedYData[SortedIndex].num; } // Finally arrange the X-arrays for (int i = 0; i < SortedYSize; i++) { if (sortedYData[i].num != 0) { m_QSorter.Sort(sortedCellsData, sortedYData[i].start, sortedYData[i].start + sortedYData[i].num - 1); } } m_sorted = true; } public int total_cells() { return m_num_used_cells; } public int scanline_num_cells(int y) { return (int)m_sorted_y.data()[y - m_min_y].num; } public void scanline_cells(int y, out cell_aa[] CellData, out int Offset) { CellData = m_sorted_cells.data(); Offset = m_sorted_y[y - m_min_y].start; } public bool sorted() { return m_sorted; } private void set_curr_cell(int x, int y) { if (m_curr_cell.not_equal(x, y, m_style_cell)) { add_curr_cell(); m_curr_cell.style(m_style_cell); m_curr_cell.x = x; m_curr_cell.y = y; m_curr_cell.cover = 0; m_curr_cell.area = 0; } } private void add_curr_cell() { if ((m_curr_cell.area | m_curr_cell.cover) != 0) { if (m_num_used_cells >= (int)cell_block_scale_e.cell_block_limit) { return; } allocate_cells_if_required(); m_cells.data()[m_num_used_cells].Set(m_curr_cell); m_num_used_cells++; #if false if(m_num_used_cells == 281) { int a = 12; } DebugFile.Print(m_num_used_cells.ToString() + ". x=" + m_curr_cell.m_x.ToString() + " y=" + m_curr_cell.m_y.ToString() + " area=" + m_curr_cell.m_area.ToString() + " cover=" + m_curr_cell.m_cover.ToString() + "\n"); #endif } } private void allocate_cells_if_required() { if (m_cells == null || (m_num_used_cells + 1) >= m_cells.Capacity()) { if (m_num_used_cells >= (int)cell_block_scale_e.cell_block_limit) { return; } int new_num_allocated_cells = m_num_used_cells + (int)cell_block_scale_e.cell_block_size; VectorPOD<cell_aa> new_cells = new VectorPOD<cell_aa>(new_num_allocated_cells); if (m_cells != null) { new_cells.CopyFrom(m_cells); } m_cells = new_cells; } } private void render_hline(int ey, int x1, int y1, int x2, int y2) { int ex1 = x1 >> (int)poly_subpixel_scale_e.poly_subpixel_shift; int ex2 = x2 >> (int)poly_subpixel_scale_e.poly_subpixel_shift; int fx1 = x1 & (int)poly_subpixel_scale_e.poly_subpixel_mask; int fx2 = x2 & (int)poly_subpixel_scale_e.poly_subpixel_mask; int delta, p, first, dx; int incr, lift, mod, rem; //trivial case. Happens often if (y1 == y2) { set_curr_cell(ex2, ey); return; } //everything is located in a single cell. That is easy! if (ex1 == ex2) { delta = y2 - y1; m_curr_cell.cover += delta; m_curr_cell.area += (fx1 + fx2) * delta; return; } //ok, we'll have to render a run of adjacent cells on the same hline... p = ((int)poly_subpixel_scale_e.poly_subpixel_scale - fx1) * (y2 - y1); first = (int)poly_subpixel_scale_e.poly_subpixel_scale; incr = 1; dx = x2 - x1; if (dx < 0) { p = fx1 * (y2 - y1); first = 0; incr = -1; dx = -dx; } delta = p / dx; mod = p % dx; if (mod < 0) { delta--; mod += dx; } m_curr_cell.cover += delta; m_curr_cell.area += (fx1 + first) * delta; ex1 += incr; set_curr_cell(ex1, ey); y1 += delta; if (ex1 != ex2) { p = (int)poly_subpixel_scale_e.poly_subpixel_scale * (y2 - y1 + delta); lift = p / dx; rem = p % dx; if (rem < 0) { lift--; rem += dx; } mod -= dx; while (ex1 != ex2) { delta = lift; mod += rem; if (mod >= 0) { mod -= dx; delta++; } m_curr_cell.cover += delta; m_curr_cell.area += (int)poly_subpixel_scale_e.poly_subpixel_scale * delta; y1 += delta; ex1 += incr; set_curr_cell(ex1, ey); } } delta = y2 - y1; m_curr_cell.cover += delta; m_curr_cell.area += (fx2 + (int)poly_subpixel_scale_e.poly_subpixel_scale - first) * delta; } private static void swap_cells(cell_aa a, cell_aa b) { cell_aa temp = a; a = b; b = temp; } private enum qsort { qsort_threshold = 9 }; } //------------------------------------------------------scanline_hit_test public class scanline_hit_test : IScanlineCache { private int m_x; private bool m_hit; public scanline_hit_test(int x) { m_x = x; m_hit = false; } public void ResetSpans() { } public void finalize(int nothing) { } public void add_cell(int x, int nothing) { if (m_x == x) m_hit = true; } public void add_span(int x, int len, int nothing) { if (m_x >= x && m_x < x + len) m_hit = true; } public int num_spans() { return 1; } public bool hit() { return m_hit; } public void reset(int min_x, int max_x) { throw new System.NotImplementedException(); } public ScanlineSpan begin() { throw new System.NotImplementedException(); } public ScanlineSpan GetNextScanlineSpan() { throw new System.NotImplementedException(); } public int y() { throw new System.NotImplementedException(); } public byte[] GetCovers() { throw new System.NotImplementedException(); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the swf-2012-01-25.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.SimpleWorkflow.Model; namespace Amazon.SimpleWorkflow { /// <summary> /// Interface for accessing SimpleWorkflow /// /// Amazon Simple Workflow Service /// <para> /// The Amazon Simple Workflow Service (Amazon SWF) makes it easy to build applications /// that use Amazon's cloud to coordinate work across distributed components. In Amazon /// SWF, a <i>task</i> represents a logical unit of work that is performed by a component /// of your workflow. Coordinating tasks in a workflow involves managing intertask dependencies, /// scheduling, and concurrency in accordance with the logical flow of the application. /// </para> /// /// <para> /// Amazon SWF gives you full control over implementing tasks and coordinating them without /// worrying about underlying complexities such as tracking their progress and maintaining /// their state. /// </para> /// /// <para> /// This documentation serves as reference only. For a broader overview of the Amazon /// SWF programming model, see the <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/">Amazon /// SWF Developer Guide</a>. /// </para> /// </summary> public partial interface IAmazonSimpleWorkflow : IDisposable { #region CountClosedWorkflowExecutions /// <summary> /// Initiates the asynchronous execution of the CountClosedWorkflowExecutions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CountClosedWorkflowExecutions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CountClosedWorkflowExecutionsResponse> CountClosedWorkflowExecutionsAsync(CountClosedWorkflowExecutionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CountOpenWorkflowExecutions /// <summary> /// Initiates the asynchronous execution of the CountOpenWorkflowExecutions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CountOpenWorkflowExecutions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CountOpenWorkflowExecutionsResponse> CountOpenWorkflowExecutionsAsync(CountOpenWorkflowExecutionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CountPendingActivityTasks /// <summary> /// Initiates the asynchronous execution of the CountPendingActivityTasks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CountPendingActivityTasks operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CountPendingActivityTasksResponse> CountPendingActivityTasksAsync(CountPendingActivityTasksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CountPendingDecisionTasks /// <summary> /// Initiates the asynchronous execution of the CountPendingDecisionTasks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CountPendingDecisionTasks operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CountPendingDecisionTasksResponse> CountPendingDecisionTasksAsync(CountPendingDecisionTasksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeprecateActivityType /// <summary> /// Initiates the asynchronous execution of the DeprecateActivityType operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeprecateActivityType operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeprecateActivityTypeResponse> DeprecateActivityTypeAsync(DeprecateActivityTypeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeprecateDomain /// <summary> /// Initiates the asynchronous execution of the DeprecateDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeprecateDomain operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeprecateDomainResponse> DeprecateDomainAsync(DeprecateDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeprecateWorkflowType /// <summary> /// Initiates the asynchronous execution of the DeprecateWorkflowType operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeprecateWorkflowType operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeprecateWorkflowTypeResponse> DeprecateWorkflowTypeAsync(DeprecateWorkflowTypeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeActivityType /// <summary> /// Initiates the asynchronous execution of the DescribeActivityType operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeActivityType operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeActivityTypeResponse> DescribeActivityTypeAsync(DescribeActivityTypeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeDomain /// <summary> /// Initiates the asynchronous execution of the DescribeDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDomain operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeDomainResponse> DescribeDomainAsync(DescribeDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeWorkflowExecution /// <summary> /// Initiates the asynchronous execution of the DescribeWorkflowExecution operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeWorkflowExecution operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeWorkflowExecutionResponse> DescribeWorkflowExecutionAsync(DescribeWorkflowExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeWorkflowType /// <summary> /// Initiates the asynchronous execution of the DescribeWorkflowType operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeWorkflowType operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeWorkflowTypeResponse> DescribeWorkflowTypeAsync(DescribeWorkflowTypeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetWorkflowExecutionHistory /// <summary> /// Initiates the asynchronous execution of the GetWorkflowExecutionHistory operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetWorkflowExecutionHistory operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetWorkflowExecutionHistoryResponse> GetWorkflowExecutionHistoryAsync(GetWorkflowExecutionHistoryRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListActivityTypes /// <summary> /// Initiates the asynchronous execution of the ListActivityTypes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListActivityTypes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListActivityTypesResponse> ListActivityTypesAsync(ListActivityTypesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListClosedWorkflowExecutions /// <summary> /// Initiates the asynchronous execution of the ListClosedWorkflowExecutions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListClosedWorkflowExecutions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListClosedWorkflowExecutionsResponse> ListClosedWorkflowExecutionsAsync(ListClosedWorkflowExecutionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListDomains /// <summary> /// Initiates the asynchronous execution of the ListDomains operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListDomains operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListDomainsResponse> ListDomainsAsync(ListDomainsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListOpenWorkflowExecutions /// <summary> /// Initiates the asynchronous execution of the ListOpenWorkflowExecutions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListOpenWorkflowExecutions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListOpenWorkflowExecutionsResponse> ListOpenWorkflowExecutionsAsync(ListOpenWorkflowExecutionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListWorkflowTypes /// <summary> /// Initiates the asynchronous execution of the ListWorkflowTypes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListWorkflowTypes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListWorkflowTypesResponse> ListWorkflowTypesAsync(ListWorkflowTypesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PollForActivityTask /// <summary> /// Initiates the asynchronous execution of the PollForActivityTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PollForActivityTask operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PollForActivityTaskResponse> PollForActivityTaskAsync(PollForActivityTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PollForDecisionTask /// <summary> /// Initiates the asynchronous execution of the PollForDecisionTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PollForDecisionTask operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PollForDecisionTaskResponse> PollForDecisionTaskAsync(PollForDecisionTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RecordActivityTaskHeartbeat /// <summary> /// Initiates the asynchronous execution of the RecordActivityTaskHeartbeat operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RecordActivityTaskHeartbeat operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RecordActivityTaskHeartbeatResponse> RecordActivityTaskHeartbeatAsync(RecordActivityTaskHeartbeatRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RegisterActivityType /// <summary> /// Initiates the asynchronous execution of the RegisterActivityType operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RegisterActivityType operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RegisterActivityTypeResponse> RegisterActivityTypeAsync(RegisterActivityTypeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RegisterDomain /// <summary> /// Initiates the asynchronous execution of the RegisterDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RegisterDomain operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RegisterDomainResponse> RegisterDomainAsync(RegisterDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RegisterWorkflowType /// <summary> /// Initiates the asynchronous execution of the RegisterWorkflowType operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RegisterWorkflowType operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RegisterWorkflowTypeResponse> RegisterWorkflowTypeAsync(RegisterWorkflowTypeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RequestCancelWorkflowExecution /// <summary> /// Initiates the asynchronous execution of the RequestCancelWorkflowExecution operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RequestCancelWorkflowExecution operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RequestCancelWorkflowExecutionResponse> RequestCancelWorkflowExecutionAsync(RequestCancelWorkflowExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RespondActivityTaskCanceled /// <summary> /// Initiates the asynchronous execution of the RespondActivityTaskCanceled operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RespondActivityTaskCanceled operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RespondActivityTaskCanceledResponse> RespondActivityTaskCanceledAsync(RespondActivityTaskCanceledRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RespondActivityTaskCompleted /// <summary> /// Initiates the asynchronous execution of the RespondActivityTaskCompleted operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RespondActivityTaskCompleted operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RespondActivityTaskCompletedResponse> RespondActivityTaskCompletedAsync(RespondActivityTaskCompletedRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RespondActivityTaskFailed /// <summary> /// Initiates the asynchronous execution of the RespondActivityTaskFailed operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RespondActivityTaskFailed operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RespondActivityTaskFailedResponse> RespondActivityTaskFailedAsync(RespondActivityTaskFailedRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RespondDecisionTaskCompleted /// <summary> /// Initiates the asynchronous execution of the RespondDecisionTaskCompleted operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RespondDecisionTaskCompleted operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RespondDecisionTaskCompletedResponse> RespondDecisionTaskCompletedAsync(RespondDecisionTaskCompletedRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SignalWorkflowExecution /// <summary> /// Initiates the asynchronous execution of the SignalWorkflowExecution operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SignalWorkflowExecution operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SignalWorkflowExecutionResponse> SignalWorkflowExecutionAsync(SignalWorkflowExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region StartWorkflowExecution /// <summary> /// Initiates the asynchronous execution of the StartWorkflowExecution operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartWorkflowExecution operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<StartWorkflowExecutionResponse> StartWorkflowExecutionAsync(StartWorkflowExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region TerminateWorkflowExecution /// <summary> /// Initiates the asynchronous execution of the TerminateWorkflowExecution operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the TerminateWorkflowExecution operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<TerminateWorkflowExecutionResponse> TerminateWorkflowExecutionAsync(TerminateWorkflowExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion } }