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. ==================================================================== */ using System; using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.SS; using NPOI.SS.Formula; using NPOI.SS.Formula.Functions; using NPOI.SS.Formula.PTG; using NPOI.SS.Formula.Udf; using NPOI.SS.UserModel; using NPOI.XSSF.Model; namespace NPOI.XSSF.UserModel { /** * Internal POI use only * * @author Josh Micich */ public class XSSFEvaluationWorkbook : IFormulaRenderingWorkbook, IEvaluationWorkbook, IFormulaParsingWorkbook { private XSSFWorkbook _uBook; public static XSSFEvaluationWorkbook Create(IWorkbook book) { if (book == null) { return null; } return new XSSFEvaluationWorkbook(book); } private XSSFEvaluationWorkbook(IWorkbook book) { _uBook = (XSSFWorkbook)book; } private int ConvertFromExternalSheetIndex(int externSheetIndex) { return externSheetIndex; } /** * @return the sheet index of the sheet with the given external index. */ public int ConvertFromExternSheetIndex(int externSheetIndex) { return externSheetIndex; } /** * @return the external sheet index of the sheet with the given internal * index. Used by some of the more obscure formula and named range things. * Fairly easy on XSSF (we think...) since the internal and external * indicies are the same */ private int ConvertToExternalSheetIndex(int sheetIndex) { return sheetIndex; } public int GetExternalSheetIndex(String sheetName) { int sheetIndex = _uBook.GetSheetIndex(sheetName); return ConvertToExternalSheetIndex(sheetIndex); } public IEvaluationName GetName(String name, int sheetIndex) { for (int i = 0; i < _uBook.NumberOfNames; i++) { IName nm = _uBook.GetNameAt(i); String nameText = nm.NameName; if (name.Equals(nameText, StringComparison.InvariantCultureIgnoreCase) && nm.SheetIndex == sheetIndex) { return new Name(_uBook.GetNameAt(i), i, this); } } return sheetIndex == -1 ? null : GetName(name, -1); } public int GetSheetIndex(IEvaluationSheet EvalSheet) { XSSFSheet sheet = ((XSSFEvaluationSheet)EvalSheet).GetXSSFSheet(); return _uBook.GetSheetIndex(sheet); } public String GetSheetName(int sheetIndex) { return _uBook.GetSheetName(sheetIndex); } public ExternalName GetExternalName(int externSheetIndex, int externNameIndex) { throw new NotImplementedException(); } public NameXPtg GetNameXPtg(String name) { IndexedUDFFinder udfFinder = (IndexedUDFFinder)GetUDFFinder(); FreeRefFunction func = udfFinder.FindFunction(name); if (func == null) return null; else return new NameXPtg(0, udfFinder.GetFunctionIndex(name)); } public String ResolveNameXText(NameXPtg n) { int idx = n.NameIndex; IndexedUDFFinder udfFinder = (IndexedUDFFinder)GetUDFFinder(); return udfFinder.GetFunctionName(idx); } public IEvaluationSheet GetSheet(int sheetIndex) { return new XSSFEvaluationSheet(_uBook.GetSheetAt(sheetIndex)); } public ExternalSheet GetExternalSheet(int externSheetIndex) { // TODO Auto-generated method stub return null; } public int GetExternalSheetIndex(String workbookName, String sheetName) { throw new Exception("not implemented yet"); } public int GetSheetIndex(String sheetName) { return _uBook.GetSheetIndex(sheetName); } public String GetSheetNameByExternSheet(int externSheetIndex) { int sheetIndex = ConvertFromExternalSheetIndex(externSheetIndex); return _uBook.GetSheetName(sheetIndex); } public String GetNameText(NamePtg namePtg) { return _uBook.GetNameAt(namePtg.Index).NameName; } public IEvaluationName GetName(NamePtg namePtg) { int ix = namePtg.Index; return new Name(_uBook.GetNameAt(ix), ix, this); } public Ptg[] GetFormulaTokens(IEvaluationCell EvalCell) { XSSFCell cell = ((XSSFEvaluationCell)EvalCell).GetXSSFCell(); XSSFEvaluationWorkbook frBook = XSSFEvaluationWorkbook.Create(_uBook); return FormulaParser.Parse(cell.CellFormula, frBook, FormulaType.Cell, _uBook.GetSheetIndex(cell.Sheet)); } public UDFFinder GetUDFFinder() { return _uBook.GetUDFFinder(); } /** * XSSF allows certain extra textual characters in the formula that * HSSF does not. As these can't be composed down to HSSF-compatible * Ptgs, this method strips them out for us. */ private String CleanXSSFFormulaText(String text) { // Newlines are allowed in XSSF text = text.Replace("\\n", "").Replace("\\r", ""); // All done with cleaning return text; } private class Name : IEvaluationName { private XSSFName _nameRecord; private int _index; private IFormulaParsingWorkbook _fpBook; public Name(IName name, int index, IFormulaParsingWorkbook fpBook) { _nameRecord = (XSSFName)name; _index = index; _fpBook = fpBook; } public Ptg[] NameDefinition { get { return FormulaParser.Parse(_nameRecord.RefersToFormula, _fpBook, FormulaType.NamedRange, _nameRecord.SheetIndex); } } public String NameText { get { return _nameRecord.NameName; } } public bool HasFormula { get { // TODO - no idea if this is right CT_DefinedName ctn = _nameRecord.GetCTName(); String strVal = ctn.Value; return !ctn.function && strVal != null && strVal.Length > 0; } } public bool IsFunctionName { get { return _nameRecord.IsFunctionName; } } public bool IsRange { get { return HasFormula; // TODO - is this right? } } public NamePtg CreatePtg() { return new NamePtg(_index); } } public SpreadsheetVersion GetSpreadsheetVersion() { return SpreadsheetVersion.EXCEL2007; } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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 Gallio.Common.Collections; using Gallio.Framework; using Gallio.Framework.Assertions; using Gallio.Common.Diagnostics; using Gallio.Common.Markup; using MbUnit.Framework; namespace Gallio.Tests.Framework.Assertions { [TestsOn(typeof(AssertionContext))] public class AssertionContextTest { [Test] public void CurrentAssertionContextIsAssociatedWithTheCurrentTestContext() { AssertionContext current = AssertionContext.CurrentContext; Assert.AreSame(TestContext.CurrentContext, current.TestContext); } [Test] public void CurrentAssertionContextIsPreservedAcrossMultipleRequests() { Assert.AreSame(AssertionContext.CurrentContext, AssertionContext.CurrentContext); } [Test] public void DifferentTestContextsHaveDifferentAssertionContexts() { AssertionContext a = null, b = null; TestStep.RunStep("A", () => a = AssertionContext.CurrentContext); TestStep.RunStep("B", () => b = AssertionContext.CurrentContext); Assert.IsNotNull(a); Assert.IsNotNull(b); Assert.AreNotSame(a, b); } [Test] public void InitialAssertionFailureBehaviorIsLogAndThrow() { Assert.AreEqual(AssertionFailureBehavior.LogAndThrow, AssertionContext.CurrentContext.AssertionFailureBehavior); } public class WhenAssertionFailureBehaviorIsLogAndThrow { [Test] public void TheAssertionIsLoggedAndCapturedButExecutionEnds() { StubAssertionFailure failure1 = new StubAssertionFailure(); StubAssertionFailure failure2 = new StubAssertionFailure(); bool completed = false; AssertionFailure[] failures = AssertionContext.CurrentContext.CaptureFailures(delegate { AssertionContext.CurrentContext.SubmitFailure(failure1); AssertionContext.CurrentContext.SubmitFailure(failure2); completed = true; }, AssertionFailureBehavior.LogAndThrow, false); Assert.AreElementsEqual(new[] { failure1 }, failures); Assert.IsTrue(failure1.WasWriteToCalled); Assert.IsFalse(failure2.WasWriteToCalled); Assert.IsFalse(completed); } [Test] public void WhenCaptureExceptionIsTrueAnExceptionIsReifiedAsAnAssertionFailure() { AssertionFailure[] failures = AssertionContext.CurrentContext.CaptureFailures(delegate { throw new InvalidOperationException("Boom"); }, AssertionFailureBehavior.LogAndThrow, true); Assert.Count(1, failures); Assert.AreEqual("An exception occurred.", failures[0].Description); Assert.Count(1, failures[0].Exceptions); Assert.Contains(failures[0].Exceptions[0].ToString(), "Boom"); } [Test] public void WhenCaptureExceptionIsFalseAnExceptionEscapesTheBlock() { Assert.Throws<InvalidOperationException>(delegate { AssertionContext.CurrentContext.CaptureFailures(delegate { throw new InvalidOperationException("Boom"); }, AssertionFailureBehavior.LogAndThrow, false); }); } [Test] [Row(true), Row(false)] public void WhenCaptureExceptionIsTrueANonSilentAssertionFailureExceptionIsReifiedAsAnAssertionFailure(bool captureExceptionAsAssertionFailure) { AssertionFailure assertionFailure = new AssertionFailureBuilder("Boom").ToAssertionFailure(); AssertionFailure[] failures = AssertionContext.CurrentContext.CaptureFailures(delegate { throw new AssertionFailureException(assertionFailure, false); }, AssertionFailureBehavior.LogAndThrow, captureExceptionAsAssertionFailure); Assert.AreElementsEqual(new[] { assertionFailure }, failures); } [Test] [Row(true), Row(false)] public void WhenCaptureExceptionIsTrueOrFalseATestExceptionEscapesTheBlock(bool captureExceptionAsAssertionFailure) { Assert.Throws<TestInconclusiveException>(delegate { AssertionContext.CurrentContext.CaptureFailures(delegate { throw new TestInconclusiveException("Boom"); }, AssertionFailureBehavior.LogAndThrow, captureExceptionAsAssertionFailure); }); } } public class WhenAssertionFailureBehaviorIsThrow { [Test] public void TheAssertionIsNotLoggedButItIsCapturedButExecutionEnds() { StubAssertionFailure failure1 = new StubAssertionFailure(); StubAssertionFailure failure2 = new StubAssertionFailure(); bool completed = false; AssertionFailure[] failures = AssertionContext.CurrentContext.CaptureFailures(delegate { AssertionContext.CurrentContext.SubmitFailure(failure1); AssertionContext.CurrentContext.SubmitFailure(failure2); completed = true; }, AssertionFailureBehavior.Throw, false); Assert.AreElementsEqual(new[] { failure1 }, failures); Assert.IsFalse(failure1.WasWriteToCalled); Assert.IsFalse(failure2.WasWriteToCalled); Assert.IsFalse(completed); } } public class WhenAssertionFailureBehaviorIsLog { [Test] public void TheAssertionIsLoggedAndCapturedAndExecutionContinues() { StubAssertionFailure failure1 = new StubAssertionFailure(); StubAssertionFailure failure2 = new StubAssertionFailure(); bool completed = false; AssertionFailure[] failures = AssertionContext.CurrentContext.CaptureFailures(delegate { AssertionContext.CurrentContext.SubmitFailure(failure1); AssertionContext.CurrentContext.SubmitFailure(failure2); completed = true; }, AssertionFailureBehavior.Log, false); Assert.AreElementsEqual(new[] { failure1, failure2 }, failures); Assert.IsTrue(failure1.WasWriteToCalled); Assert.IsTrue(failure2.WasWriteToCalled); Assert.IsTrue(completed); } } public class WhenAssertionFailureBehaviorIsCaptureAndContinue { [Test] public void TheAssertionIsNotLoggedButIsCapturedAndExecutionContinues() { StubAssertionFailure failure1 = new StubAssertionFailure(); StubAssertionFailure failure2 = new StubAssertionFailure(); bool completed = false; AssertionFailure[] failures = AssertionContext.CurrentContext.CaptureFailures(delegate { AssertionContext.CurrentContext.SubmitFailure(failure1); AssertionContext.CurrentContext.SubmitFailure(failure2); completed = true; }, AssertionFailureBehavior.CaptureAndContinue, false); Assert.AreElementsEqual(new[] { failure1, failure2 }, failures); Assert.IsFalse(failure1.WasWriteToCalled); Assert.IsFalse(failure2.WasWriteToCalled); Assert.IsTrue(completed); } } public class WhenAssertionFailureBehaviorIsDiscard { [Test] public void NothingHappens() { StubAssertionFailure failure1 = new StubAssertionFailure(); StubAssertionFailure failure2 = new StubAssertionFailure(); bool completed = false; AssertionFailure[] failures = AssertionContext.CurrentContext.CaptureFailures(delegate { AssertionContext.CurrentContext.SubmitFailure(failure1); AssertionContext.CurrentContext.SubmitFailure(failure2); completed = true; }, AssertionFailureBehavior.Discard, false); Assert.IsEmpty(failures); Assert.IsFalse(failure1.WasWriteToCalled); Assert.IsFalse(failure2.WasWriteToCalled); Assert.IsTrue(completed); } } private sealed class StubAssertionFailure : AssertionFailure { private bool wasWriteToCalled; public StubAssertionFailure() : base("Description", "Message", new StackTraceData("stackTrace"), EmptyArray<LabeledValue>.Instance, EmptyArray<ExceptionData>.Instance, EmptyArray<AssertionFailure>.Instance) { } public bool WasWriteToCalled { get { return wasWriteToCalled; } } public override void WriteTo(MarkupStreamWriter writer) { wasWriteToCalled = true; base.WriteTo(writer); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ODataValidator.RuleEngine.Common { /// <summary> /// Class to keep cross-component constants /// </summary> public static class Constants { /// <summary> /// The timeout value of web request. /// </summary> public const string WebRequestTimeOut = "8000"; /// <summary> /// HTTP header Content-Type for json-formatted payload /// </summary> public const string ContentTypeJson = @"application/json"; /// <summary> /// HTTP header Content-Type for text/plain payload /// </summary> public const string ContentTypeTextPlain = @"text/plain"; /// <summary> /// Regular expression for json content type /// </summary> public const string RegexContentTypeJson = @"application/json"; /// <summary> /// HTTP header Content-Type for atom-formatted payload /// </summary> public const string ContentTypeAtom = @"application/atom+xml"; /// <summary> /// HTTP header Content-Type for atomsvc-formatted payload /// </summary> public const string ContentTypeAtomSvc = @"application/atomsvc+xml"; /// <summary> /// Regular expression for atompub content type /// </summary> public const string RegexContentTypeAtom = @"application/atom\+xml"; /// <summary> /// HTTP header Content-Type for xml-formatted payload /// </summary> public const string ContentTypeXml = @"application/xml"; /// <summary> /// Regular expression for xml content type /// </summary> public const string RegexContentTypeXml = @"application/xml"; /// <summary> /// HTTP header Content-Type for text/xml /// </summary> public const string ContentTypeTextXml = @"text/xml"; /// <summary> /// Regular expression for text content type /// </summary> public const string RegexContentTypeTextXml = @"text/xml"; /// <summary> /// HTTP header Content-Type for image/jpeg /// </summary> public const string ContentTypeJPEGImage = @"image/jpeg"; /// <summary> /// HTTP header Content-Type for image/* /// </summary> public const string ContentTypeImage = @"image/.*"; /// <summary> /// Regular expression for image content type /// </summary> public const string RegexContentTypeImage = @"image/.*"; /// <summary> /// appendix segment to OData service base uri for endpoint of metadata document /// </summary> public const string OptionMetadata = "/" + Constants.Metadata; /// <summary> /// Keyword of content_type. /// </summary> public const string ContentType = "Content-Type"; /// <summary> /// Keyword of DataServiceVersion. /// </summary> public const string DataServiceVersion = "DataServiceVersion"; /// <summary> /// Keyword of OData-Version. /// </summary> public const string ODataVersion = "OData-Version"; /// <summary> /// Keyword of Access-Control-Allow-Headers. /// </summary> public const string AllowHeaders = "Access-Control-Allow-Headers"; /// <summary> /// Keyword of AcceptHeader. /// </summary> public const string AcceptHeader = "Accept"; /// <summary> /// Keyword of MaxDataServiceVersion. /// </summary> public const string MaxVersion = "MaxDataServiceVersion"; /// <summary> /// keyword of metadata document /// </summary> public const string Metadata = "$metadata"; /// <summary> /// HTTP request header Accept to expect atom/xml response /// </summary> public const string AcceptHeaderAtom = @"*/*; q=0.2, application/atom+xml, application/xml; q=0.5"; /// <summary> /// HTTP request header Accept to expect json response /// </summary> public const string AcceptHeaderJson = @"application/json"; /// <summary> /// Undefined HTTP request header Accept to expect a 415 Unsupported Media Type HTTP status code. /// </summary> public const string UndefinedAcceptHeader = @"odata/test"; /// <summary> /// HTTP request odata v3 header Accept to expect json verbose format /// </summary> public const string V3AcceptHeaderJsonVerbose = AcceptHeaderJson + ";odata=verbose"; /// <summary> /// HTTP request odata v3 header Accept to expect json response with full metadata /// </summary> public const string V3AcceptHeaderJsonFullMetadata = AcceptHeaderJson + @";odata=fullmetadata"; /// <summary> /// HTTP request odata v3 header Accept to expect json response with minimal metadata /// </summary> public const string V3AcceptHeaderJsonMinimalMetadata = AcceptHeaderJson + @";odata=minimalmetadata"; /// <summary> /// HTTP request odata v3 header Accept to expect json response with no metadata /// </summary> public const string V3AcceptHeaderJsonNoMetadata = AcceptHeaderJson + @";odata=nometadata"; /// <summary> /// HTTP request odata v4 header Accept to expect json response with full metadata /// </summary> public const string V4AcceptHeaderJsonFullMetadata = AcceptHeaderJson + @";odata.metadata=full"; /// <summary> /// HTTP request odata v4 header Accept to expect json response with minimal metadata /// </summary> public const string V4AcceptHeaderJsonMinimalMetadata = AcceptHeaderJson + @";odata.metadata=minimal"; /// <summary> /// HTTP request odata v4 header Accept to expect json response with no metadata /// </summary> public const string V4AcceptHeaderJsonNoMetadata = AcceptHeaderJson + @";odata.metadata=none"; /// <summary> /// expecting request context to be atom/xml format /// </summary> public const string FormatAtomOrXml = "atompub"; /// <summary> /// expecting request context to be json format /// </summary> public const string FormatJson = "json"; /// <summary> /// expecting request odata v3 context to be json verbose format /// </summary> public const string V3FormatJsonVerbose = FormatJson + ";odata=verbose"; /// <summary> /// expecting request odata v3 context to be json format and full metadata /// </summary> public const string V3FormatJsonFullMetadata = FormatJson + ";odata=fullmetadata"; /// <summary> /// expecting request odata v3 context to be json format and minimal metadata /// </summary> public const string V3FormatJsonMinimalMetadata = FormatJson + ";odata=minimalmetadata"; /// <summary> /// expecting request odata v3 context to be json format and minimal metadata /// </summary> public const string V3FormatJsonNoMetadata = FormatJson + ";odata=nometadata"; /// <summary> /// expecting request odata v4 context to be json format and full metadata /// </summary> public const string V4FormatJsonFullMetadata = FormatJson + ";odata.metadata=full"; /// <summary> /// expecting request odata v4 context to be json format and minimal metadata /// </summary> public const string V4FormatJsonMinimalMetadata = FormatJson + ";odata.metadata=minimal"; /// <summary> /// expecting request odata v4 context to be json format and minimal metadata /// </summary> public const string V4FormatJsonNoMetadata = FormatJson + ";odata.metadata=none"; /// <summary> /// classification of success /// </summary> public const string ClassificationSuccess = "success"; /// <summary> /// classification of error /// </summary> public const string ClassificationError = "error"; /// <summary> /// classification of warning /// </summary> public const string ClassificationWarning = "warning"; /// <summary> /// classification of recommendation /// </summary> public const string ClassificationRecommendation = "recommendation"; /// <summary> /// classification of not-applicable /// </summary> public const string ClassificationNotApplicable = "notApplicable"; /// <summary> /// classification of aborted /// </summary> public const string ClassificationAborted = "aborted"; /// <summary> /// classification of pending /// </summary> public const string ClassificationPending = "pending"; /// <summary> /// classification of pending /// </summary> public const string ClassificationSkip = "skip"; /// <summary> /// The default target uri string of offline service context. /// This is pretty much an dummy string serving as a placeholder of offline context. /// </summary> public const string DefaultOfflineTarget = "http://offline"; /// <summary> /// The property name of __deferred in v3 json verbose response. /// </summary> public const string JsonVerboseDeferredPropertyName = @"__deferred"; /// <summary> /// The property name of content_type in v3 json verbose response. /// </summary> public const string JsonVerboseContent_TypeProperty = "content_type"; /// <summary> /// The "d" mark in v3 json verbose response. /// </summary> public const string BeginMarkD = @"d"; /// <summary> /// The results property in v3 json verbose response. /// </summary> public const string Results = @"results"; /// <summary> /// The result property in v3 json verbose response. /// </summary> public const string Result = @"result"; /// <summary> /// The property name of __metadata in v3 json verbose response. /// </summary> public const string JsonVerboseMetadataPropertyName = @"__metadata"; /// <summary> /// The property name of uri in v3 json verbose response. /// </summary> public const string JsonVerboseUriPropertyName = @"uri"; /// <summary> /// The first property name of Odata v3 json response. /// </summary> public const string OdataV3JsonIdentity = "odata.metadata"; /// <summary> /// The first property name of Odata v4 json response. /// </summary> public const string OdataV4JsonIdentity = "@odata.context"; /// <summary> /// The identity of Service Document's odata.metadata value in Odata v3 json response. /// </summary> public const string JsonSvcDocIdentity = "$metadata"; /// <summary> /// The identity of Entity's odata.metadata value in Odata v3 json response. /// </summary> public const string V3JsonEntityIdentity = "@Element"; /// <summary> /// The identity of Entity's odata.context value in Odata v4 json response. /// </summary> public const string V4JsonEntityIdentity = "$entity"; /// <summary> /// The identity of feed's odata.metadata value in Odata v3 json response. /// </summary> public const string JsonFeedIdentity = "$metadata#"; /// <summary> /// The identity of Odata v3 json verbose error response. /// </summary> public const string V3JsonVerboseErrorResponseIdentity = "error"; /// <summary> /// The identity of Odata v3 json light error response. /// </summary> public const string V3JsonLightErrorResponseIdentity = "odata.error"; /// <summary> /// The identity of Odata v4 json light error response. /// </summary> public const string V4JsonLightErrorResponseIdentity = "error"; /// <summary> /// The message object name in json error response. /// </summary> public const string MessageNameInJsonErrorResponse = "message"; /// <summary> /// The identity of feed's odata.metadata value in Odata v3 json response. /// </summary> public const string V3JsonDeltaResponseIdentity = "@delta"; /// <summary> /// The identity of feed's odata.context value in Odata v4 json response. /// </summary> public const string V4JsonDeltaResponseIdentity = "$delta"; /// <summary> /// The identity of collection entity reference in Odata v4 json response. /// </summary> public const string V4JsonCollectionEntityRefIdentity = @"$metadata#Collection($ref)"; /// <summary> /// The identity of entity reference in Odata v4 json response. /// </summary> public const string V4JsonEntityRefIdentity = @"$metadata#$ref"; /// <summary> /// The "id" property of deleted entity in delta response. /// </summary> public const string ID = "id"; /// <summary> /// The "reason" property of deleted entity in delta response. /// </summary> public const string Reason = "reason"; /// <summary> /// The "source" property of link object in delta response. /// </summary> public const string Source = "source"; /// <summary> /// The "relationship" property of link object in delta response. /// </summary> public const string Relationship = "relationship"; /// <summary> /// The "target" property of link object in delta response. /// </summary> public const string Target = "target"; /// <summary> /// The value property name. /// </summary> public const string Value = "value"; /// <summary> /// The kind property name. /// </summary> public const string Kind = "kind"; /// <summary> /// The url property name. /// </summary> public const string Url = "url"; /// <summary> /// The name property name. /// </summary> public const string Name = "name"; /// <summary> /// The type property name. /// </summary> public const string Type = "type"; /// <summary> /// The EntitySets property name. /// </summary> public const string EntitySets = "EntitySets"; /// <summary> /// The EntitySet property name. /// </summary> public const string EntitySet = "EntitySet"; /// <summary> /// The FunctionImport kind value. /// </summary> public const string FunctionImport = "FunctionImport"; /// <summary> /// The Name attribute name. /// </summary> public const string NameAttribute = "Name"; /// <summary> /// The EntityType attribute name. /// </summary> public const string EntityTypeAttribute = "EntityType"; /// <summary> /// The odata namespace with dot. /// </summary> public const string OdataNS = "odata."; /// <summary> /// The v4 odata namespace with dot. /// </summary> public const string V4OdataNS = "@odata."; /// <summary> /// The identity of entry's edit link name in Odata json response. /// </summary> public const string OdataEditLink = @"odata.editLink"; /// <summary> /// The identity of v4 entry's edit link name in Odata json response. /// </summary> public const string V4OdataEditLink = @"@odata.editLink"; /// <summary> /// The identity of navigation link property's suffix name in Odata json response. /// </summary> public const string OdataNavigationLinkPropertyNameSuffix = @"@odata.navigationLink"; /// <summary> /// The identity of association link property's suffix name in Odata json response. /// </summary> public const string OdataAssociationLinkPropertyNameSuffix = @"@odata.associationLink"; /// <summary> /// The v3 odata.type property name. /// </summary> public const string OdataType = "odata.type"; /// <summary> /// The v4 odata.type property name. /// </summary> public const string V4OdataType = "@odata.type"; /// <summary> /// The v3 odata.id property name. /// </summary> public const string OdataId = "odata.id"; /// <summary> /// The v4 odata.id property name. /// </summary> public const string V4OdataId = "@odata.id"; /// <summary> /// The v3 odata.etag annotation. /// </summary> public const string OdataEtag = "odata.etag"; /// <summary> /// The v4 odata.etag annotation. /// </summary> public const string V4OdataEtag = "@odata.etag"; /// <summary> /// The odata.readLink annotation. /// </summary> public const string OdataReadLink = "odata.readLink"; /// <summary> /// The v4 odata.readLink annotation. /// </summary> public const string V4OdataReadLink = "@odata.readLink"; /// <summary> /// The v3 odata.count property name. /// </summary> public const string OdataCount = "odata.count"; /// <summary> /// The v4 odata.count property name. /// </summary> public const string V4OdataCount = "@odata.count"; /// <summary> /// The odata.nextLink property name. /// </summary> public const string OdataNextLink = "odata.nextLink"; /// <summary> /// The v4 odata.nextLink property name. /// </summary> public const string V4OdataNextLink = "@odata.nextLink"; /// <summary> /// The odata.deltaLink property name. /// </summary> public const string OdataDeltaLink = "odata.deltaLink"; /// <summary> /// The v4 odata.deltaLink property name. /// </summary> public const string V4OdataDeltaLink = "@odata.deltaLink"; /// <summary> /// The start string of media entity annotations. /// </summary> public const string OdataMedia = "odata.media"; /// <summary> /// The start string of v4 media entity annotations. /// </summary> public const string V4OdataMedia = "@odata.media"; /// <summary> /// The odata.mediaEtag annotation. /// </summary> public const string OdataMediaEtag = "odata.mediaEtag"; /// <summary> /// The v4 odata.mediaEtag annotation. /// </summary> public const string V4OdataMediaEtag = "@odata.mediaEtag"; /// <summary> /// The identity of entry's media edit link name in Odata json response. /// </summary> public const string OdataMediaEditLink = @"odata.mediaEditLink"; /// <summary> /// The identity of v4 entry's media edit link name in Odata json response. /// </summary> public const string V4OdataMediaEditLink = @"@odata.mediaEditLink"; /// <summary> /// The identity of entry's media read link name in Odata json response. /// </summary> public const string OdataMediaReadLink = @"odata.mediaReadLink"; /// <summary> /// The identity of v4 entry's media read link name in Odata json response. /// </summary> public const string V4OdataMediaReadLink = @"@odata.mediaReadLink"; /// <summary> /// The odata.mediaContentType annotation. /// </summary> public const string OdataMediaContentType = "odata.mediaContentType"; /// <summary> /// The v4 odata.mediaContentType annotation. /// </summary> public const string V4OdataMediaContentType = "@odata.mediaContentType"; /// <summary> /// The v3 service supports odata.streaming. /// </summary> public const string OdataStreaming = @"streaming=true"; /// <summary> /// The v4 service supports odata.streaming. /// </summary> public const string V4OdataStreaming = @"odata.streaming=true"; /// <summary> /// The prefix "Edm." in metadata. /// </summary> public const string EdmDotPrefix = @"Edm."; /// <summary> /// The namespace http://www.w3.org/2007/app /// </summary> public const string NSApp = @"http://www.w3.org/2007/app"; /// <summary> /// The namespace http://www.w3.org/2005/Atom /// </summary> public const string NSAtom = @"http://www.w3.org/2005/Atom"; /// <summary> /// The namespace http://schemas.microsoft.com/ado/2007/08/dataservices/metadata. /// </summary> public const string V3NSMetadata = @"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"; /// <summary> /// The namespace http://docs.oasis-open.org/odata/ns/metadata. /// </summary> public const string NSMetadata = @"http://docs.oasis-open.org/odata/ns/metadata"; /// <summary> /// The namespace http://schemas.microsoft.com/ado/2007/08/dataservices /// </summary> public const string V3NSData = @"http://schemas.microsoft.com/ado/2007/08/dataservices"; /// <summary> /// The namespace http://docs.oasis-open.org/odata/ns/data. /// </summary> public const string V4NSData = @"http://docs.oasis-open.org/odata/ns/data"; /// <summary> /// The scheme URL http://docs.oasis-open.org/odata/ns/scheme /// </summary> public const string SchemeURL = @"http://docs.oasis-open.org/odata/ns/scheme"; /// <summary> /// The scheme URL http://docs.oasis-open.org/odata/ns/edmx /// </summary> public const string EdmxNs = @"http://docs.oasis-open.org/odata/ns/edmx"; /// <summary> /// The namespace http://docs.oasis-open.org/odata/ns/relatedlinks /// </summary> public const string NSAssociationLink = @"http://docs.oasis-open.org/odata/ns/relatedlinks"; /// <summary> /// The EDM namespace http://docs.oasis-open.org/odata/ns/edm /// </summary> public const string EdmNs = @"http://docs.oasis-open.org/odata/ns/edm"; /// <summary> /// The immutable Collection regular expressions. /// </summary> public const string ImmutableCollectionRegexPattern = @"^#*Collection\((\w+\.)*\w+\)$"; /// <summary> /// The mutable Collection regular expressions. /// </summary> public const string MutableCollectionRegexPattern = @"^#*Collection\({0}\.\w+\)$"; /// <summary> /// The normal properties' data of an updatable entity. /// </summary> public const string UpdateData = @"[OData Validation Tool] Updated data"; /// <summary> /// The OData Test Key Name. /// </summary> public const string ODataKeyName = "ODataKeyName"; /// <summary> /// The Location header. /// </summary> public const string LocationHeader = "LocationHeader"; /// <summary> /// Error URI template. /// </summary> public const string ErrorURI = "<i><b>{0}</b> {1} <b>{2}</b></i> <br>"; /// <summary> /// Error message template. /// </summary> public const string ErrorMsg = "<font color=\"red\"> {0} </font><br>"; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/logging/v2/logging_config.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Logging.V2 { /// <summary>Holder for reflection information generated from google/logging/v2/logging_config.proto</summary> public static partial class LoggingConfigReflection { #region Descriptor /// <summary>File descriptor for google/logging/v2/logging_config.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static LoggingConfigReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiZnb29nbGUvbG9nZ2luZy92Mi9sb2dnaW5nX2NvbmZpZy5wcm90bxIRZ29v", "Z2xlLmxvZ2dpbmcudjIaHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8a", "G2dvb2dsZS9wcm90b2J1Zi9lbXB0eS5wcm90bxofZ29vZ2xlL3Byb3RvYnVm", "L3RpbWVzdGFtcC5wcm90byK9AgoHTG9nU2luaxIMCgRuYW1lGAEgASgJEhMK", "C2Rlc3RpbmF0aW9uGAMgASgJEg4KBmZpbHRlchgFIAEoCRJHChVvdXRwdXRf", "dmVyc2lvbl9mb3JtYXQYBiABKA4yKC5nb29nbGUubG9nZ2luZy52Mi5Mb2dT", "aW5rLlZlcnNpb25Gb3JtYXQSFwoPd3JpdGVyX2lkZW50aXR5GAggASgJEi4K", "CnN0YXJ0X3RpbWUYCiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1w", "EiwKCGVuZF90aW1lGAsgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFt", "cCI/Cg1WZXJzaW9uRm9ybWF0Eh4KGlZFUlNJT05fRk9STUFUX1VOU1BFQ0lG", "SUVEEAASBgoCVjIQARIGCgJWMRACIkkKEExpc3RTaW5rc1JlcXVlc3QSDgoG", "cGFyZW50GAEgASgJEhIKCnBhZ2VfdG9rZW4YAiABKAkSEQoJcGFnZV9zaXpl", "GAMgASgFIlcKEUxpc3RTaW5rc1Jlc3BvbnNlEikKBXNpbmtzGAEgAygLMhou", "Z29vZ2xlLmxvZ2dpbmcudjIuTG9nU2luaxIXCg9uZXh0X3BhZ2VfdG9rZW4Y", "AiABKAkiIwoOR2V0U2lua1JlcXVlc3QSEQoJc2lua19uYW1lGAEgASgJIm0K", "EUNyZWF0ZVNpbmtSZXF1ZXN0Eg4KBnBhcmVudBgBIAEoCRIoCgRzaW5rGAIg", "ASgLMhouZ29vZ2xlLmxvZ2dpbmcudjIuTG9nU2luaxIeChZ1bmlxdWVfd3Jp", "dGVyX2lkZW50aXR5GAMgASgIInAKEVVwZGF0ZVNpbmtSZXF1ZXN0EhEKCXNp", "bmtfbmFtZRgBIAEoCRIoCgRzaW5rGAIgASgLMhouZ29vZ2xlLmxvZ2dpbmcu", "djIuTG9nU2luaxIeChZ1bmlxdWVfd3JpdGVyX2lkZW50aXR5GAMgASgIIiYK", "EURlbGV0ZVNpbmtSZXF1ZXN0EhEKCXNpbmtfbmFtZRgBIAEoCTL+BAoPQ29u", "ZmlnU2VydmljZVYyEn0KCUxpc3RTaW5rcxIjLmdvb2dsZS5sb2dnaW5nLnYy", "Lkxpc3RTaW5rc1JlcXVlc3QaJC5nb29nbGUubG9nZ2luZy52Mi5MaXN0U2lu", "a3NSZXNwb25zZSIlgtPkkwIfEh0vdjIve3BhcmVudD1wcm9qZWN0cy8qfS9z", "aW5rcxJ0CgdHZXRTaW5rEiEuZ29vZ2xlLmxvZ2dpbmcudjIuR2V0U2lua1Jl", "cXVlc3QaGi5nb29nbGUubG9nZ2luZy52Mi5Mb2dTaW5rIiqC0+STAiQSIi92", "Mi97c2lua19uYW1lPXByb2plY3RzLyovc2lua3MvKn0SewoKQ3JlYXRlU2lu", "axIkLmdvb2dsZS5sb2dnaW5nLnYyLkNyZWF0ZVNpbmtSZXF1ZXN0GhouZ29v", "Z2xlLmxvZ2dpbmcudjIuTG9nU2luayIrgtPkkwIlIh0vdjIve3BhcmVudD1w", "cm9qZWN0cy8qfS9zaW5rczoEc2luaxKAAQoKVXBkYXRlU2luaxIkLmdvb2ds", "ZS5sb2dnaW5nLnYyLlVwZGF0ZVNpbmtSZXF1ZXN0GhouZ29vZ2xlLmxvZ2dp", "bmcudjIuTG9nU2luayIwgtPkkwIqGiIvdjIve3NpbmtfbmFtZT1wcm9qZWN0", "cy8qL3NpbmtzLyp9OgRzaW5rEnYKCkRlbGV0ZVNpbmsSJC5nb29nbGUubG9n", "Z2luZy52Mi5EZWxldGVTaW5rUmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5F", "bXB0eSIqgtPkkwIkKiIvdjIve3NpbmtfbmFtZT1wcm9qZWN0cy8qL3Npbmtz", "Lyp9QoEBChVjb20uZ29vZ2xlLmxvZ2dpbmcudjJCEkxvZ2dpbmdDb25maWdQ", "cm90b1ABWjhnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlz", "L2xvZ2dpbmcvdjI7bG9nZ2luZ6oCF0dvb2dsZS5DbG91ZC5Mb2dnaW5nLlYy", "YgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.LogSink), global::Google.Cloud.Logging.V2.LogSink.Parser, new[]{ "Name", "Destination", "Filter", "OutputVersionFormat", "WriterIdentity", "StartTime", "EndTime" }, null, new[]{ typeof(global::Google.Cloud.Logging.V2.LogSink.Types.VersionFormat) }, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.ListSinksRequest), global::Google.Cloud.Logging.V2.ListSinksRequest.Parser, new[]{ "Parent", "PageToken", "PageSize" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.ListSinksResponse), global::Google.Cloud.Logging.V2.ListSinksResponse.Parser, new[]{ "Sinks", "NextPageToken" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.GetSinkRequest), global::Google.Cloud.Logging.V2.GetSinkRequest.Parser, new[]{ "SinkName" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.CreateSinkRequest), global::Google.Cloud.Logging.V2.CreateSinkRequest.Parser, new[]{ "Parent", "Sink", "UniqueWriterIdentity" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.UpdateSinkRequest), global::Google.Cloud.Logging.V2.UpdateSinkRequest.Parser, new[]{ "SinkName", "Sink", "UniqueWriterIdentity" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.DeleteSinkRequest), global::Google.Cloud.Logging.V2.DeleteSinkRequest.Parser, new[]{ "SinkName" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Describes a sink used to export log entries to one of the following /// destinations in any project: a Cloud Storage bucket, a BigQuery dataset, or a /// Cloud Pub/Sub topic. A logs filter controls which log entries are /// exported. The sink must be created within a project or organization. /// </summary> public sealed partial class LogSink : pb::IMessage<LogSink> { private static readonly pb::MessageParser<LogSink> _parser = new pb::MessageParser<LogSink>(() => new LogSink()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<LogSink> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LogSink() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LogSink(LogSink other) : this() { name_ = other.name_; destination_ = other.destination_; filter_ = other.filter_; outputVersionFormat_ = other.outputVersionFormat_; writerIdentity_ = other.writerIdentity_; StartTime = other.startTime_ != null ? other.StartTime.Clone() : null; EndTime = other.endTime_ != null ? other.EndTime.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LogSink Clone() { return new LogSink(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Required. The client-assigned sink identifier, unique within the /// project. Example: `"my-syslog-errors-to-pubsub"`. Sink identifiers are /// limited to 100 characters and can include only the following characters: /// upper and lower-case alphanumeric characters, underscores, hyphens, and /// periods. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "destination" field.</summary> public const int DestinationFieldNumber = 3; private string destination_ = ""; /// <summary> /// Required. The export destination: /// /// "storage.googleapis.com/[GCS_BUCKET]" /// "bigquery.googleapis.com/projects/[PROJECT_ID]/datasets/[DATASET]" /// "pubsub.googleapis.com/projects/[PROJECT_ID]/topics/[TOPIC_ID]" /// /// The sink's `writer_identity`, set when the sink is created, must /// have permission to write to the destination or else the log /// entries are not exported. For more information, see /// [Exporting Logs With Sinks](/logging/docs/api/tasks/exporting-logs). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Destination { get { return destination_; } set { destination_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "filter" field.</summary> public const int FilterFieldNumber = 5; private string filter_ = ""; /// <summary> /// Optional. /// An [advanced logs filter](/logging/docs/view/advanced_filters). The only /// exported log entries are those that are in the resource owning the sink and /// that match the filter. The filter must use the log entry format specified /// by the `output_version_format` parameter. For example, in the v2 format: /// /// logName="projects/[PROJECT_ID]/logs/[LOG_ID]" AND severity>=ERROR /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Filter { get { return filter_; } set { filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "output_version_format" field.</summary> public const int OutputVersionFormatFieldNumber = 6; private global::Google.Cloud.Logging.V2.LogSink.Types.VersionFormat outputVersionFormat_ = 0; /// <summary> /// Optional. The log entry format to use for this sink's exported log /// entries. The v2 format is used by default. /// **The v1 format is deprecated** and should be used only as part of a /// migration effort to v2. /// See [Migration to the v2 API](/logging/docs/api/v2/migration-to-v2). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Logging.V2.LogSink.Types.VersionFormat OutputVersionFormat { get { return outputVersionFormat_; } set { outputVersionFormat_ = value; } } /// <summary>Field number for the "writer_identity" field.</summary> public const int WriterIdentityFieldNumber = 8; private string writerIdentity_ = ""; /// <summary> /// Output only. An IAM identity&amp;mdash;a service account or group&amp;mdash;under /// which Stackdriver Logging writes the exported log entries to the sink's /// destination. This field is set by /// [sinks.create](/logging/docs/api/reference/rest/v2/projects.sinks/create) /// and /// [sinks.update](/logging/docs/api/reference/rest/v2/projects.sinks/update), /// based on the setting of `unique_writer_identity` in those methods. /// /// Until you grant this identity write-access to the destination, log entry /// exports from this sink will fail. For more information, /// see [Granting access for a /// resource](/iam/docs/granting-roles-to-service-accounts#granting_access_to_a_service_account_for_a_resource). /// Consult the destination service's documentation to determine the /// appropriate IAM roles to assign to the identity. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string WriterIdentity { get { return writerIdentity_; } set { writerIdentity_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "start_time" field.</summary> public const int StartTimeFieldNumber = 10; private global::Google.Protobuf.WellKnownTypes.Timestamp startTime_; /// <summary> /// Optional. The time at which this sink will begin exporting log entries. /// Log entries are exported only if their timestamp is not earlier than the /// start time. The default value of this field is the time the sink is /// created or updated. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp StartTime { get { return startTime_; } set { startTime_ = value; } } /// <summary>Field number for the "end_time" field.</summary> public const int EndTimeFieldNumber = 11; private global::Google.Protobuf.WellKnownTypes.Timestamp endTime_; /// <summary> /// Optional. The time at which this sink will stop exporting log entries. Log /// entries are exported only if their timestamp is earlier than the end time. /// If this field is not supplied, there is no end time. If both a start time /// and an end time are provided, then the end time must be later than the /// start time. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp EndTime { get { return endTime_; } set { endTime_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as LogSink); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(LogSink other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Destination != other.Destination) return false; if (Filter != other.Filter) return false; if (OutputVersionFormat != other.OutputVersionFormat) return false; if (WriterIdentity != other.WriterIdentity) return false; if (!object.Equals(StartTime, other.StartTime)) return false; if (!object.Equals(EndTime, other.EndTime)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Destination.Length != 0) hash ^= Destination.GetHashCode(); if (Filter.Length != 0) hash ^= Filter.GetHashCode(); if (OutputVersionFormat != 0) hash ^= OutputVersionFormat.GetHashCode(); if (WriterIdentity.Length != 0) hash ^= WriterIdentity.GetHashCode(); if (startTime_ != null) hash ^= StartTime.GetHashCode(); if (endTime_ != null) hash ^= EndTime.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Destination.Length != 0) { output.WriteRawTag(26); output.WriteString(Destination); } if (Filter.Length != 0) { output.WriteRawTag(42); output.WriteString(Filter); } if (OutputVersionFormat != 0) { output.WriteRawTag(48); output.WriteEnum((int) OutputVersionFormat); } if (WriterIdentity.Length != 0) { output.WriteRawTag(66); output.WriteString(WriterIdentity); } if (startTime_ != null) { output.WriteRawTag(82); output.WriteMessage(StartTime); } if (endTime_ != null) { output.WriteRawTag(90); output.WriteMessage(EndTime); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Destination.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Destination); } if (Filter.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Filter); } if (OutputVersionFormat != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) OutputVersionFormat); } if (WriterIdentity.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(WriterIdentity); } if (startTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartTime); } if (endTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EndTime); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(LogSink other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Destination.Length != 0) { Destination = other.Destination; } if (other.Filter.Length != 0) { Filter = other.Filter; } if (other.OutputVersionFormat != 0) { OutputVersionFormat = other.OutputVersionFormat; } if (other.WriterIdentity.Length != 0) { WriterIdentity = other.WriterIdentity; } if (other.startTime_ != null) { if (startTime_ == null) { startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } StartTime.MergeFrom(other.StartTime); } if (other.endTime_ != null) { if (endTime_ == null) { endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } EndTime.MergeFrom(other.EndTime); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 26: { Destination = input.ReadString(); break; } case 42: { Filter = input.ReadString(); break; } case 48: { outputVersionFormat_ = (global::Google.Cloud.Logging.V2.LogSink.Types.VersionFormat) input.ReadEnum(); break; } case 66: { WriterIdentity = input.ReadString(); break; } case 82: { if (startTime_ == null) { startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(startTime_); break; } case 90: { if (endTime_ == null) { endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(endTime_); break; } } } } #region Nested types /// <summary>Container for nested types declared in the LogSink message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Available log entry formats. Log entries can be written to Stackdriver /// Logging in either format and can be exported in either format. /// Version 2 is the preferred format. /// </summary> public enum VersionFormat { /// <summary> /// An unspecified format version that will default to V2. /// </summary> [pbr::OriginalName("VERSION_FORMAT_UNSPECIFIED")] Unspecified = 0, /// <summary> /// `LogEntry` version 2 format. /// </summary> [pbr::OriginalName("V2")] V2 = 1, /// <summary> /// `LogEntry` version 1 format. /// </summary> [pbr::OriginalName("V1")] V1 = 2, } } #endregion } /// <summary> /// The parameters to `ListSinks`. /// </summary> public sealed partial class ListSinksRequest : pb::IMessage<ListSinksRequest> { private static readonly pb::MessageParser<ListSinksRequest> _parser = new pb::MessageParser<ListSinksRequest>(() => new ListSinksRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ListSinksRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListSinksRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListSinksRequest(ListSinksRequest other) : this() { parent_ = other.parent_; pageToken_ = other.pageToken_; pageSize_ = other.pageSize_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListSinksRequest Clone() { return new ListSinksRequest(this); } /// <summary>Field number for the "parent" field.</summary> public const int ParentFieldNumber = 1; private string parent_ = ""; /// <summary> /// Required. The parent resource whose sinks are to be listed. /// Examples: `"projects/my-logging-project"`, `"organizations/123456789"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Parent { get { return parent_; } set { parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "page_token" field.</summary> public const int PageTokenFieldNumber = 2; private string pageToken_ = ""; /// <summary> /// Optional. If present, then retrieve the next batch of results from the /// preceding call to this method. `pageToken` must be the value of /// `nextPageToken` from the previous response. The values of other method /// parameters should be identical to those in the previous call. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string PageToken { get { return pageToken_; } set { pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "page_size" field.</summary> public const int PageSizeFieldNumber = 3; private int pageSize_; /// <summary> /// Optional. The maximum number of results to return from this request. /// Non-positive values are ignored. The presence of `nextPageToken` in the /// response indicates that more results might be available. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int PageSize { get { return pageSize_; } set { pageSize_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ListSinksRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ListSinksRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Parent != other.Parent) return false; if (PageToken != other.PageToken) return false; if (PageSize != other.PageSize) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Parent.Length != 0) hash ^= Parent.GetHashCode(); if (PageToken.Length != 0) hash ^= PageToken.GetHashCode(); if (PageSize != 0) hash ^= PageSize.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Parent.Length != 0) { output.WriteRawTag(10); output.WriteString(Parent); } if (PageToken.Length != 0) { output.WriteRawTag(18); output.WriteString(PageToken); } if (PageSize != 0) { output.WriteRawTag(24); output.WriteInt32(PageSize); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Parent.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent); } if (PageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken); } if (PageSize != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ListSinksRequest other) { if (other == null) { return; } if (other.Parent.Length != 0) { Parent = other.Parent; } if (other.PageToken.Length != 0) { PageToken = other.PageToken; } if (other.PageSize != 0) { PageSize = other.PageSize; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Parent = input.ReadString(); break; } case 18: { PageToken = input.ReadString(); break; } case 24: { PageSize = input.ReadInt32(); break; } } } } } /// <summary> /// Result returned from `ListSinks`. /// </summary> public sealed partial class ListSinksResponse : pb::IMessage<ListSinksResponse> { private static readonly pb::MessageParser<ListSinksResponse> _parser = new pb::MessageParser<ListSinksResponse>(() => new ListSinksResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ListSinksResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListSinksResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListSinksResponse(ListSinksResponse other) : this() { sinks_ = other.sinks_.Clone(); nextPageToken_ = other.nextPageToken_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ListSinksResponse Clone() { return new ListSinksResponse(this); } /// <summary>Field number for the "sinks" field.</summary> public const int SinksFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Cloud.Logging.V2.LogSink> _repeated_sinks_codec = pb::FieldCodec.ForMessage(10, global::Google.Cloud.Logging.V2.LogSink.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Logging.V2.LogSink> sinks_ = new pbc::RepeatedField<global::Google.Cloud.Logging.V2.LogSink>(); /// <summary> /// A list of sinks. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Logging.V2.LogSink> Sinks { get { return sinks_; } } /// <summary>Field number for the "next_page_token" field.</summary> public const int NextPageTokenFieldNumber = 2; private string nextPageToken_ = ""; /// <summary> /// If there might be more results than appear in this response, then /// `nextPageToken` is included. To get the next set of results, call the same /// method again using the value of `nextPageToken` as `pageToken`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string NextPageToken { get { return nextPageToken_; } set { nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ListSinksResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ListSinksResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!sinks_.Equals(other.sinks_)) return false; if (NextPageToken != other.NextPageToken) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= sinks_.GetHashCode(); if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { sinks_.WriteTo(output, _repeated_sinks_codec); if (NextPageToken.Length != 0) { output.WriteRawTag(18); output.WriteString(NextPageToken); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += sinks_.CalculateSize(_repeated_sinks_codec); if (NextPageToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ListSinksResponse other) { if (other == null) { return; } sinks_.Add(other.sinks_); if (other.NextPageToken.Length != 0) { NextPageToken = other.NextPageToken; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { sinks_.AddEntriesFrom(input, _repeated_sinks_codec); break; } case 18: { NextPageToken = input.ReadString(); break; } } } } } /// <summary> /// The parameters to `GetSink`. /// </summary> public sealed partial class GetSinkRequest : pb::IMessage<GetSinkRequest> { private static readonly pb::MessageParser<GetSinkRequest> _parser = new pb::MessageParser<GetSinkRequest>(() => new GetSinkRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetSinkRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetSinkRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetSinkRequest(GetSinkRequest other) : this() { sinkName_ = other.sinkName_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetSinkRequest Clone() { return new GetSinkRequest(this); } /// <summary>Field number for the "sink_name" field.</summary> public const int SinkNameFieldNumber = 1; private string sinkName_ = ""; /// <summary> /// Required. The parent resource name of the sink: /// /// "projects/[PROJECT_ID]/sinks/[SINK_ID]" /// "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" /// /// Example: `"projects/my-project-id/sinks/my-sink-id"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SinkName { get { return sinkName_; } set { sinkName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetSinkRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetSinkRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (SinkName != other.SinkName) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (SinkName.Length != 0) hash ^= SinkName.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (SinkName.Length != 0) { output.WriteRawTag(10); output.WriteString(SinkName); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (SinkName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SinkName); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetSinkRequest other) { if (other == null) { return; } if (other.SinkName.Length != 0) { SinkName = other.SinkName; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { SinkName = input.ReadString(); break; } } } } } /// <summary> /// The parameters to `CreateSink`. /// </summary> public sealed partial class CreateSinkRequest : pb::IMessage<CreateSinkRequest> { private static readonly pb::MessageParser<CreateSinkRequest> _parser = new pb::MessageParser<CreateSinkRequest>(() => new CreateSinkRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CreateSinkRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateSinkRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateSinkRequest(CreateSinkRequest other) : this() { parent_ = other.parent_; Sink = other.sink_ != null ? other.Sink.Clone() : null; uniqueWriterIdentity_ = other.uniqueWriterIdentity_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CreateSinkRequest Clone() { return new CreateSinkRequest(this); } /// <summary>Field number for the "parent" field.</summary> public const int ParentFieldNumber = 1; private string parent_ = ""; /// <summary> /// Required. The resource in which to create the sink: /// /// "projects/[PROJECT_ID]" /// "organizations/[ORGANIZATION_ID]" /// /// Examples: `"projects/my-logging-project"`, `"organizations/123456789"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Parent { get { return parent_; } set { parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "sink" field.</summary> public const int SinkFieldNumber = 2; private global::Google.Cloud.Logging.V2.LogSink sink_; /// <summary> /// Required. The new sink, whose `name` parameter is a sink identifier that /// is not already in use. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Logging.V2.LogSink Sink { get { return sink_; } set { sink_ = value; } } /// <summary>Field number for the "unique_writer_identity" field.</summary> public const int UniqueWriterIdentityFieldNumber = 3; private bool uniqueWriterIdentity_; /// <summary> /// Optional. Determines the kind of IAM identity returned as `writer_identity` /// in the new sink. If this value is omitted or set to false, and if the /// sink's parent is a project, then the value returned as `writer_identity` is /// `[email protected]`, the same identity used before the addition of /// writer identities to this API. The sink's destination must be in the same /// project as the sink itself. /// /// If this field is set to true, or if the sink is owned by a non-project /// resource such as an organization, then the value of `writer_identity` will /// be a unique service account used only for exports from the new sink. For /// more information, see `writer_identity` in [LogSink][google.logging.v2.LogSink]. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool UniqueWriterIdentity { get { return uniqueWriterIdentity_; } set { uniqueWriterIdentity_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CreateSinkRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CreateSinkRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Parent != other.Parent) return false; if (!object.Equals(Sink, other.Sink)) return false; if (UniqueWriterIdentity != other.UniqueWriterIdentity) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Parent.Length != 0) hash ^= Parent.GetHashCode(); if (sink_ != null) hash ^= Sink.GetHashCode(); if (UniqueWriterIdentity != false) hash ^= UniqueWriterIdentity.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Parent.Length != 0) { output.WriteRawTag(10); output.WriteString(Parent); } if (sink_ != null) { output.WriteRawTag(18); output.WriteMessage(Sink); } if (UniqueWriterIdentity != false) { output.WriteRawTag(24); output.WriteBool(UniqueWriterIdentity); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Parent.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent); } if (sink_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Sink); } if (UniqueWriterIdentity != false) { size += 1 + 1; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CreateSinkRequest other) { if (other == null) { return; } if (other.Parent.Length != 0) { Parent = other.Parent; } if (other.sink_ != null) { if (sink_ == null) { sink_ = new global::Google.Cloud.Logging.V2.LogSink(); } Sink.MergeFrom(other.Sink); } if (other.UniqueWriterIdentity != false) { UniqueWriterIdentity = other.UniqueWriterIdentity; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Parent = input.ReadString(); break; } case 18: { if (sink_ == null) { sink_ = new global::Google.Cloud.Logging.V2.LogSink(); } input.ReadMessage(sink_); break; } case 24: { UniqueWriterIdentity = input.ReadBool(); break; } } } } } /// <summary> /// The parameters to `UpdateSink`. /// </summary> public sealed partial class UpdateSinkRequest : pb::IMessage<UpdateSinkRequest> { private static readonly pb::MessageParser<UpdateSinkRequest> _parser = new pb::MessageParser<UpdateSinkRequest>(() => new UpdateSinkRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UpdateSinkRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateSinkRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateSinkRequest(UpdateSinkRequest other) : this() { sinkName_ = other.sinkName_; Sink = other.sink_ != null ? other.Sink.Clone() : null; uniqueWriterIdentity_ = other.uniqueWriterIdentity_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UpdateSinkRequest Clone() { return new UpdateSinkRequest(this); } /// <summary>Field number for the "sink_name" field.</summary> public const int SinkNameFieldNumber = 1; private string sinkName_ = ""; /// <summary> /// Required. The full resource name of the sink to update, including the /// parent resource and the sink identifier: /// /// "projects/[PROJECT_ID]/sinks/[SINK_ID]" /// "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" /// /// Example: `"projects/my-project-id/sinks/my-sink-id"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SinkName { get { return sinkName_; } set { sinkName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "sink" field.</summary> public const int SinkFieldNumber = 2; private global::Google.Cloud.Logging.V2.LogSink sink_; /// <summary> /// Required. The updated sink, whose name is the same identifier that appears /// as part of `sink_name`. If `sink_name` does not exist, then /// this method creates a new sink. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Logging.V2.LogSink Sink { get { return sink_; } set { sink_ = value; } } /// <summary>Field number for the "unique_writer_identity" field.</summary> public const int UniqueWriterIdentityFieldNumber = 3; private bool uniqueWriterIdentity_; /// <summary> /// Optional. See /// [sinks.create](/logging/docs/api/reference/rest/v2/projects.sinks/create) /// for a description of this field. When updating a sink, the effect of this /// field on the value of `writer_identity` in the updated sink depends on both /// the old and new values of this field: /// /// + If the old and new values of this field are both false or both true, /// then there is no change to the sink's `writer_identity`. /// + If the old value was false and the new value is true, then /// `writer_identity` is changed to a unique service account. /// + It is an error if the old value was true and the new value is false. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool UniqueWriterIdentity { get { return uniqueWriterIdentity_; } set { uniqueWriterIdentity_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UpdateSinkRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UpdateSinkRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (SinkName != other.SinkName) return false; if (!object.Equals(Sink, other.Sink)) return false; if (UniqueWriterIdentity != other.UniqueWriterIdentity) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (SinkName.Length != 0) hash ^= SinkName.GetHashCode(); if (sink_ != null) hash ^= Sink.GetHashCode(); if (UniqueWriterIdentity != false) hash ^= UniqueWriterIdentity.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (SinkName.Length != 0) { output.WriteRawTag(10); output.WriteString(SinkName); } if (sink_ != null) { output.WriteRawTag(18); output.WriteMessage(Sink); } if (UniqueWriterIdentity != false) { output.WriteRawTag(24); output.WriteBool(UniqueWriterIdentity); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (SinkName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SinkName); } if (sink_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Sink); } if (UniqueWriterIdentity != false) { size += 1 + 1; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UpdateSinkRequest other) { if (other == null) { return; } if (other.SinkName.Length != 0) { SinkName = other.SinkName; } if (other.sink_ != null) { if (sink_ == null) { sink_ = new global::Google.Cloud.Logging.V2.LogSink(); } Sink.MergeFrom(other.Sink); } if (other.UniqueWriterIdentity != false) { UniqueWriterIdentity = other.UniqueWriterIdentity; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { SinkName = input.ReadString(); break; } case 18: { if (sink_ == null) { sink_ = new global::Google.Cloud.Logging.V2.LogSink(); } input.ReadMessage(sink_); break; } case 24: { UniqueWriterIdentity = input.ReadBool(); break; } } } } } /// <summary> /// The parameters to `DeleteSink`. /// </summary> public sealed partial class DeleteSinkRequest : pb::IMessage<DeleteSinkRequest> { private static readonly pb::MessageParser<DeleteSinkRequest> _parser = new pb::MessageParser<DeleteSinkRequest>(() => new DeleteSinkRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<DeleteSinkRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DeleteSinkRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DeleteSinkRequest(DeleteSinkRequest other) : this() { sinkName_ = other.sinkName_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DeleteSinkRequest Clone() { return new DeleteSinkRequest(this); } /// <summary>Field number for the "sink_name" field.</summary> public const int SinkNameFieldNumber = 1; private string sinkName_ = ""; /// <summary> /// Required. The full resource name of the sink to delete, including the /// parent resource and the sink identifier: /// /// "projects/[PROJECT_ID]/sinks/[SINK_ID]" /// "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" /// /// It is an error if the sink does not exist. Example: /// `"projects/my-project-id/sinks/my-sink-id"`. It is an error if /// the sink does not exist. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SinkName { get { return sinkName_; } set { sinkName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as DeleteSinkRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(DeleteSinkRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (SinkName != other.SinkName) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (SinkName.Length != 0) hash ^= SinkName.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (SinkName.Length != 0) { output.WriteRawTag(10); output.WriteString(SinkName); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (SinkName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SinkName); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(DeleteSinkRequest other) { if (other == null) { return; } if (other.SinkName.Length != 0) { SinkName = other.SinkName; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { SinkName = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
/* Copyright 2017 Pranavkumar Patel 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; namespace GridPointCode { public static class GPC { const string CHARACTERS = "0123456789CDFGHJKLMNPRTVWXY"; //base27 const ulong ELEVEN = 205881132094649; //For Uniformity public struct Coordinates { public readonly double Latitude; public readonly double Longitude; public Coordinates(double latitude, double longitude) { Latitude = latitude; Longitude = longitude; } }; struct CoordinateSeven { public int[] LatitudeSeven; public int[] LongitudeSeven; public CoordinateSeven(int[] latitudeSeven, int[] longitudeSeven) { LatitudeSeven = latitudeSeven; LongitudeSeven = longitudeSeven; } }; struct CoordinateSignWhole { public int LatitudeSign; public int LatitudeWhole; public int LongitudeSign; public int LongitudeWhole; public CoordinateSignWhole(int latitudeSign,int latitudeWhole, int longitudeSign, int longitudeWhole) { LatitudeSign = latitudeSign; LatitudeWhole = latitudeWhole; LongitudeSign = longitudeSign; LongitudeWhole = longitudeWhole; } }; /* PART 1 : ENCODE */ //Get a Grid Point Code public static string GetGridPointCode(double latitude, double longitude) { return GetGridPointCode(latitude, longitude, true); } public static string GetGridPointCode(double latitude, double longitude, bool formatted) { double Latitude = latitude; //Latitude double Longitude = longitude; //Longitude /* Validating Latitude and Longitude values */ if (Latitude <= -90 || Latitude >= 90) { throw new ArgumentOutOfRangeException("Latitude", Latitude, "Latitude value must be between -90 to 90."); } if (Longitude <= -180 || Longitude >= 180) { throw new ArgumentOutOfRangeException("Longitude", Longitude, "Longitude value must be between -180 to 180."); } /* Getting a Point Number */ ulong Point = GetPointNumber(Latitude, Longitude); /* Encode Point */ string GridPointCode = EncodePoint(Point + ELEVEN); /* Format GridPointCode */ if (formatted) { GridPointCode = FormatGPC(GridPointCode); } return GridPointCode; } //Get Point from Coordinates static ulong GetPointNumber(double latitude, double longitude) { int[] LatitudeSeven = GetCoordinateSeven(latitude); int[] LongitudeSeven = GetCoordinateSeven(longitude); //Whole-Number Part CoordinateSignWhole SignWhole = new CoordinateSignWhole(LatitudeSeven[0], LatitudeSeven[1], LongitudeSeven[0], LongitudeSeven[1]); ulong Point = (ulong)(Math.Pow(10,10) * GetCombinationNumber(SignWhole)); //Fractional Part int Power = 9; for (int index = 2; index <= 6; index++) { Point = Point + (ulong)(Math.Pow(10,Power--) * LongitudeSeven[index]); Point = Point + (ulong)(Math.Pow(10,Power--) * LatitudeSeven[index]); } return Point; } //Break down coordinate into seven parts static int[] GetCoordinateSeven(double coordinate) { int[] Result = new int[7]; //Sign Result[0] = (coordinate < 0 ? -1 : 1); //Whole-Number Result[1] = (int)Math.Truncate(Math.Abs(coordinate)); //Fractional decimal AbsCoordinate = (decimal)Math.Abs(coordinate); decimal Fractional = AbsCoordinate - (int)Math.Truncate(AbsCoordinate); decimal Power10; for (int x = 1; x <= 5; x++) { Power10 = Fractional * 10; Result[x + 1] = (int)Math.Truncate(Power10); Fractional = Power10 - Result[x + 1]; } return Result; } //Get Combination Number of Whole-Numbers static int GetCombinationNumber(CoordinateSignWhole signWhole) { int AssignedLongitude = (signWhole.LongitudeWhole * 2) + (signWhole.LongitudeSign == -1 ? 1 : 0); int AssignedLatitude = (signWhole.LatitudeWhole * 2) + (signWhole.LatitudeSign == -1 ? 1 : 0); int MaxSum = 538; int Sum = AssignedLongitude + AssignedLatitude; int Combination = 0; if (Sum <= 179) { for (int xSum = (Sum - 1); xSum >= 0; xSum--) { Combination += xSum + 1; } Combination += AssignedLongitude + 1; } else if (Sum <= 359) { Combination += 16290; Combination += (Sum - 180) * 180; Combination += 180 - AssignedLatitude; } else if (Sum <= 538) { Combination += 48690; for (int xSum = (Sum - 1); xSum >= 360; xSum--) { Combination += MaxSum - xSum + 1; } Combination += 180 - AssignedLatitude; } return Combination; } //Encode Point to GPC static string EncodePoint(ulong point) { ulong Point = point; string Result = string.Empty; ulong Base = Convert.ToUInt64(CHARACTERS.Length); if (Point == 0) { Result += CHARACTERS[0]; } else { while (Point > 0) { Result = CHARACTERS[Convert.ToInt32(Point % Base)] + Result; Point /= Base; } } return Result; } //Format GPC static string FormatGPC(string gridPointCode) { string Result = "#"; for (int index = 0; index < gridPointCode.Length; index++) { if (index == 4 || index == 8) { Result += "-"; } Result += gridPointCode.Substring(index, 1); } return Result; } /* PART 2 : DECODE */ //Get Coordinates from GPC public static Coordinates GetCoordinates(string gridPointCode) { /* Unformatting and Validating GPC */ string GridPointCode = UnformatNValidateGPC(gridPointCode); /* Getting a Point Number */ ulong Point = DecodeToPoint(GridPointCode) - ELEVEN; /* Getting Coordinates from Point */ return GetCoordinates(Point); } //Remove format and validate GPC static string UnformatNValidateGPC(string gridPointCode) { string GridPointCode = gridPointCode.Replace(" ", "").Replace("-", "").Replace("#", "").Trim().ToUpperInvariant(); if (GridPointCode.Length != 11) { throw new ArgumentOutOfRangeException("GridPointCode",GridPointCode,"Length of GPC must be 11."); } foreach (char character in GridPointCode) { if (!CHARACTERS.Contains(character.ToString())) { throw new ArgumentOutOfRangeException("character",character,"Invalid character in GPC."); } } return GridPointCode; } //Decode string to Point static ulong DecodeToPoint(string gridPointCode) { ulong Result = 0; ulong Base = Convert.ToUInt64(CHARACTERS.Length); for (int i = 0; i < gridPointCode.Length; i++) { Result *= Base; char character = gridPointCode[i]; Result += Convert.ToUInt64(CHARACTERS.IndexOf(character)); } return Result; } //Get a Coordinates from Point static Coordinates GetCoordinates(ulong point) { int Combination = (int)Math.Truncate((point / Math.Pow(10, 10))); ulong Fractional = (ulong)(point - (Combination * Math.Pow(10, 10))); return GetCoordinates(GetCoordinateSeven(Combination, Fractional)); } //Combine Seven Parts to Coordinate static Coordinates GetCoordinates(CoordinateSeven CSeven) { int Power = 0; int TempLatitude = 0; int TempLongitude = 0; for (int x = 6; x >= 1; x--) { TempLatitude += (int)(CSeven.LatitudeSeven[x] * Math.Pow(10, Power)); TempLongitude += (int)(CSeven.LongitudeSeven[x] * Math.Pow(10, Power++)); } double Latitude = (TempLatitude / Math.Pow(10, 5)) * CSeven.LatitudeSeven[0]; double Longitude = (TempLongitude / Math.Pow(10, 5)) * CSeven.LongitudeSeven[0]; return new Coordinates(Latitude, Longitude); } //Get Seven Parts of Coordinate static CoordinateSeven GetCoordinateSeven(int combination, ulong fractional) { int[] LongitudeSeven = new int[7]; int[] LatitudeSeven = new int[7]; CoordinateSignWhole SignWhole = GetWholesFromCombination(combination); LongitudeSeven[0] = SignWhole.LongitudeSign; LongitudeSeven[1] = SignWhole.LongitudeWhole; LatitudeSeven[0] = SignWhole.LatitudeSign; LatitudeSeven[1] = SignWhole.LatitudeWhole; int Power = 9; for (int x = 2; x <= 6; x++) { LongitudeSeven[x] = (int)(((ulong)(Math.Truncate(fractional / Math.Pow(10, Power--)))) % 10); LatitudeSeven[x] = (int)(((ulong)(Math.Truncate(fractional / Math.Pow(10, Power--)))) % 10); } return new CoordinateSeven(LatitudeSeven, LongitudeSeven); } //Get Whole-Numbers from Combination number static CoordinateSignWhole GetWholesFromCombination(int combination) { int MaxSum = 538; int XSum = 0; int XCombination = 0; int Sum = 0; int MaxCombination = 0; int AssignedLongitude = 0; int AssignedLatitude = 0; if (combination <= 16290) { for (XSum = 0; MaxCombination < combination; XSum++) { MaxCombination += XSum + 1; } Sum = XSum - 1; XCombination = MaxCombination - (Sum + 1); AssignedLongitude = combination - XCombination - 1; AssignedLatitude = Sum - AssignedLongitude; } else if (combination <= 48690) { XCombination = 16290; XSum = 179; bool IsLast = (combination - XCombination) % 180 == 0; int Pre = ((combination - XCombination) / 180) - (IsLast ? 1 : 0); XSum += Pre; XCombination += Pre * 180; Sum = XSum + 1; AssignedLatitude = 180 - (combination - XCombination); AssignedLongitude = Sum - AssignedLatitude; } else if (combination <= 64800) { XCombination = 48690; XSum = 359; MaxCombination += XCombination; for (XSum = 360; MaxCombination < combination; XSum++) { MaxCombination += (MaxSum - XSum + 1); } Sum = XSum - 1; XCombination = MaxCombination - (MaxSum - Sum + 1); AssignedLatitude = 180 - (combination - XCombination); AssignedLongitude = Sum - AssignedLatitude; } // CoordinateSignWhole Result = new CoordinateSignWhole(); Result.LongitudeSign = (AssignedLongitude % 2 != 0 ? -1 : 1); Result.LongitudeWhole = (Result.LongitudeSign == -1 ? (--AssignedLongitude / 2) : (AssignedLongitude / 2)); Result.LatitudeSign = (AssignedLatitude % 2 != 0 ? -1 : 1); Result.LatitudeWhole = (Result.LatitudeSign == -1 ? (--AssignedLatitude / 2) : (AssignedLatitude / 2)); return Result; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text.RegularExpressions; using System.Reflection; using Nwc.XmlRpc; using OpenMetaverse; using OpenMetaverse.Packets; using GridProxy; namespace GridProxy { public class ProxyFrame { public Proxy proxy; private Dictionary<string, CommandDelegate> commandDelegates = new Dictionary<string, CommandDelegate>(); private UUID agentID; private UUID sessionID; private UUID inventoryRoot; private bool logLogin = false; private string[] args; public delegate void CommandDelegate(string[] words); public string[] Args { get { return args; } } public UUID AgentID { get { return agentID; } } public UUID SessionID { get { return sessionID; } } public UUID InventoryRoot { get { return inventoryRoot; } } public void AddCommand(string cmd, CommandDelegate deleg) { commandDelegates[cmd] = deleg; } public ProxyFrame(string[] args) { //bool externalPlugin = false; this.args = args; ProxyConfig proxyConfig = new ProxyConfig("GridProxy", "Austin Jennings / Andrew Ortman", args); proxy = new Proxy(proxyConfig); // add delegates for login proxy.SetLoginRequestDelegate(new XmlRpcRequestDelegate(LoginRequest)); proxy.SetLoginResponseDelegate(new XmlRpcResponseDelegate(LoginResponse)); // add a delegate for outgoing chat proxy.AddDelegate(PacketType.ChatFromViewer, Direction.Outgoing, new PacketDelegate(ChatFromViewerOut)); // handle command line arguments foreach (string arg in args) if (arg == "--log-login") logLogin = true; else if (arg.Substring(0, 2) == "--") { int ipos = arg.IndexOf("="); if (ipos != -1) { string sw = arg.Substring(0, ipos); string val = arg.Substring(ipos + 1); Console.WriteLine("arg '" + sw + "' val '" + val + "'"); if (sw == "--load") { //externalPlugin = true; LoadPlugin(val); } } } commandDelegates["/load"] = new CommandDelegate(CmdLoad); } private void CmdLoad(string[] words) { if (words.Length != 2) SayToUser("Usage: /load <plugin name>"); else { try { LoadPlugin(words[1]); } catch (Exception e) { Console.WriteLine(e.ToString()); } } } public void LoadPlugin(string name) { Assembly assembly = Assembly.LoadFile(Path.GetFullPath(name)); foreach (Type t in assembly.GetTypes()) { try { if (t.IsSubclassOf(typeof(ProxyPlugin))) { ConstructorInfo info = t.GetConstructor(new Type[] { typeof(ProxyFrame) }); ProxyPlugin plugin = (ProxyPlugin)info.Invoke(new object[] { this }); plugin.Init(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } } // LoginRequest: dump a login request to the console private void LoginRequest(XmlRpcRequest request) { if (logLogin) { Console.WriteLine("==> Login Request"); Console.WriteLine(request); } } // Loginresponse: dump a login response to the console private void LoginResponse(XmlRpcResponse response) { System.Collections.Hashtable values = (System.Collections.Hashtable)response.Value; if (values.Contains("agent_id")) agentID = new UUID((string)values["agent_id"]); if (values.Contains("session_id")) sessionID = new UUID((string)values["session_id"]); if (values.Contains("inventory-root")) { inventoryRoot = new UUID( (string)((System.Collections.Hashtable)(((System.Collections.ArrayList)values["inventory-root"])[0]))["folder_id"] ); Console.WriteLine("inventory root: " + inventoryRoot); } if (logLogin) { Console.WriteLine("<== Login Response"); Console.WriteLine(response); } } // ChatFromViewerOut: outgoing ChatFromViewer delegate; check for Analyst commands private Packet ChatFromViewerOut(Packet packet, IPEndPoint sim) { // deconstruct the packet ChatFromViewerPacket cpacket = (ChatFromViewerPacket)packet; string message = System.Text.Encoding.UTF8.GetString(cpacket.ChatData.Message).Replace("\0", ""); if (message.Length > 1 && message[0] == '/') { string[] words = message.Split(' '); if (commandDelegates.ContainsKey(words[0])) { // this is an Analyst command; act on it and drop the chat packet ((CommandDelegate)commandDelegates[words[0]])(words); return null; } } return packet; } // SayToUser: send a message to the user as in-world chat public void SayToUser(string message) { ChatFromSimulatorPacket packet = new ChatFromSimulatorPacket(); packet.ChatData.FromName = Utils.StringToBytes("GridProxy"); packet.ChatData.SourceID = UUID.Random(); packet.ChatData.OwnerID = agentID; packet.ChatData.SourceType = (byte)2; packet.ChatData.ChatType = (byte)1; packet.ChatData.Audible = (byte)1; packet.ChatData.Position = new Vector3(0, 0, 0); packet.ChatData.Message = Utils.StringToBytes(message); proxy.InjectPacket(packet, Direction.Incoming); } } public abstract class ProxyPlugin : MarshalByRefObject { // public abstract ProxyPlugin(ProxyFrame main); public abstract void Init(); } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon 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.Collections.Generic; using NUnit.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenMetaverse; using KellermanSoftware.CompareNetObjects; using OpenSim.Framework; using System.IO; using System.Xml.Serialization; namespace OpenSim.Region.FrameworkTests { [TestFixture] public class XMLSerializerTests { private readonly List<string> PrimCompareIgnoreList = new List<string> { "ParentGroup", "FullUpdateCounter", "TerseUpdateCounter", "TimeStamp", "SerializedVelocity", "InventorySerial", "Rezzed" }; [TestFixtureSetUp] public void Setup() { } [Test] public void TestGroupSerializationDeserialization() { var sop1 = SceneUtil.RandomSOP("Root", 1); var sop2 = SceneUtil.RandomSOP("Child1", 2); var sop3 = SceneUtil.RandomSOP("Child2", 3); SceneObjectGroup group = new SceneObjectGroup(sop1); group.AddPart(sop2); group.AddPart(sop3); SceneObjectGroup deserGroup = null; string grpBytes = null; Assert.DoesNotThrow(() => { grpBytes = SceneObjectSerializer.ToXml2Format(group, true); }); Assert.NotNull(grpBytes); Assert.DoesNotThrow(() => { deserGroup = SceneObjectSerializer.FromXml2Format(grpBytes); }); CompareObjects comp = new CompareObjects(); comp.CompareStaticFields = false; comp.CompareStaticProperties = false; comp.ElementsToIgnore = PrimCompareIgnoreList; Assert.IsTrue(comp.Compare(group, deserGroup), comp.DifferencesString); } [Test] public void TestPrimitiveBaseShapeDeserialization() { var shape = SceneUtil.MockPrmitiveBaseShape();; var serializer = new XmlSerializer(shape.GetType()); Assert.NotNull(serializer); string shapeBytes = null; Assert.DoesNotThrow(() => { using (StringWriter stringwriter = new System.IO.StringWriter()) { serializer.Serialize(stringwriter, shape); shapeBytes = stringwriter.ToString(); } }); Assert.NotNull(shapeBytes); PrimitiveBaseShape deserShape = null; Assert.DoesNotThrow(() => { using (StringReader stringReader = new System.IO.StringReader(shapeBytes)) { deserShape = (PrimitiveBaseShape)serializer.Deserialize(stringReader); } }); CompareObjects comp = new CompareObjects(); comp.CompareStaticFields = false; comp.CompareStaticProperties = false; Assert.IsTrue(comp.Compare(shape, deserShape), comp.DifferencesString); } [Test] public void TestNullMediaListIsNotAnError() { var sop1 = SceneUtil.RandomSOP("Root", 1); var sop2 = SceneUtil.RandomSOP("Child1", 2); var sop3 = SceneUtil.RandomSOP("Child2", 3); SceneObjectGroup group = new SceneObjectGroup(sop1); group.AddPart(sop2); group.AddPart(sop3); sop1.Shape.Media = null; SceneObjectGroup deserGroup = null; string grpBytes = null; Assert.DoesNotThrow(() => { grpBytes = SceneObjectSerializer.ToXml2Format(group, true); }); Assert.NotNull(grpBytes); Assert.DoesNotThrow(() => { deserGroup = SceneObjectSerializer.FromXml2Format(grpBytes); }); } [Test] public void TestNullMediaEntryIsNotAnError() { var sop1 = SceneUtil.RandomSOP("Root", 1); var sop2 = SceneUtil.RandomSOP("Child1", 2); var sop3 = SceneUtil.RandomSOP("Child2", 3); sop1.Shape.Media = new PrimitiveBaseShape.PrimMedia(3); sop1.Shape.Media[0] = null; sop1.Shape.Media[1] = new MediaEntry(); sop1.Shape.Media[2] = null; SceneObjectGroup group = new SceneObjectGroup(sop1); group.AddPart(sop2); group.AddPart(sop3); SceneObjectGroup deserGroup = null; string grpBytes = null; Assert.DoesNotThrow(() => { grpBytes = SceneObjectSerializer.ToXml2Format(group, true); }); Assert.NotNull(grpBytes); Assert.DoesNotThrow(() => { deserGroup = SceneObjectSerializer.FromXml2Format(grpBytes); }); } [Test] public void TestRenderMaterialsSerialization() { var sop1 = SceneUtil.RandomSOP("Root", 1); var sop2 = SceneUtil.RandomSOP("Child1", 2); var sop3 = SceneUtil.RandomSOP("Child2", 3); var mat1 = new RenderMaterial(UUID.Random(), UUID.Random()); var mat2 = new RenderMaterial(UUID.Random(), UUID.Random()); sop1.Shape.RenderMaterials.AddMaterial(mat1); sop2.Shape.RenderMaterials.AddMaterial(mat2); SceneObjectGroup group = new SceneObjectGroup(sop1); group.AddPart(sop2); group.AddPart(sop3); SceneObjectGroup deserGroup = null; string grpBytes = null; Assert.DoesNotThrow(() => { grpBytes = SceneObjectSerializer.ToXml2Format(group, true); }); Assert.NotNull(grpBytes); Assert.DoesNotThrow(() => { deserGroup = SceneObjectSerializer.FromXml2Format(grpBytes); }); var newsop1 = deserGroup.GetChildPart(1); var newsop2 = deserGroup.GetChildPart(2); var newsop3 = deserGroup.GetChildPart(3); Assert.That(sop1.Shape.RenderMaterials, Is.EqualTo(newsop1.Shape.RenderMaterials)); Assert.That(sop2.Shape.RenderMaterials, Is.EqualTo(newsop2.Shape.RenderMaterials)); Assert.That(sop3.Shape.RenderMaterials, Is.EqualTo(newsop3.Shape.RenderMaterials)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace System.Diagnostics { internal static partial class ProcessManager { /// <summary>Gets the IDs of all processes on the current machine.</summary> public static int[] GetProcessIds() { return EnumerableHelpers.ToArray(EnumerateProcessIds()); } /// <summary>Gets process infos for each process on the specified machine.</summary> /// <param name="machineName">The target machine.</param> /// <returns>An array of process infos, one per found process.</returns> public static ProcessInfo[] GetProcessInfos(string machineName) { ThrowIfRemoteMachine(machineName); int[] procIds = GetProcessIds(machineName); // Iterate through all process IDs to load information about each process var reusableReader = new ReusableTextReader(); var processes = new List<ProcessInfo>(procIds.Length); foreach (int pid in procIds) { ProcessInfo pi = CreateProcessInfo(pid, reusableReader); if (pi != null) { processes.Add(pi); } } return processes.ToArray(); } /// <summary>Gets an array of module infos for the specified process.</summary> /// <param name="processId">The ID of the process whose modules should be enumerated.</param> /// <returns>The array of modules.</returns> internal static ProcessModuleCollection GetModules(int processId) { var modules = new ProcessModuleCollection(0); // Process from the parsed maps file each entry representing a module foreach (Interop.procfs.ParsedMapsModule entry in Interop.procfs.ParseMapsModules(processId)) { int sizeOfImage = (int)(entry.AddressRange.Value - entry.AddressRange.Key); // A single module may be split across multiple map entries; consolidate based on // the name and address ranges of sequential entries. if (modules.Count > 0) { ProcessModule module = modules[modules.Count - 1]; if (module.FileName == entry.FileName && ((long)module.BaseAddress + module.ModuleMemorySize == entry.AddressRange.Key)) { // Merge this entry with the previous one module.ModuleMemorySize += sizeOfImage; continue; } } // It's not a continuation of a previous entry but a new one: add it. unsafe { modules.Add(new ProcessModule() { FileName = entry.FileName, ModuleName = Path.GetFileName(entry.FileName), BaseAddress = new IntPtr(unchecked((void*)entry.AddressRange.Key)), ModuleMemorySize = sizeOfImage, EntryPointAddress = IntPtr.Zero // unknown }); } } // Return the set of modules found return modules; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary> /// Creates a ProcessInfo from the specified process ID. /// </summary> internal static ProcessInfo CreateProcessInfo(int pid, ReusableTextReader reusableReader = null) { if (reusableReader == null) { reusableReader = new ReusableTextReader(); } Interop.procfs.ParsedStat stat; return Interop.procfs.TryReadStatFile(pid, out stat, reusableReader) ? CreateProcessInfo(stat, reusableReader) : null; } /// <summary> /// Creates a ProcessInfo from the data parsed from a /proc/pid/stat file and the associated tasks directory. /// </summary> internal static ProcessInfo CreateProcessInfo(Interop.procfs.ParsedStat procFsStat, ReusableTextReader reusableReader) { int pid = procFsStat.pid; var pi = new ProcessInfo() { ProcessId = pid, ProcessName = procFsStat.comm, BasePriority = (int)procFsStat.nice, VirtualBytes = (long)procFsStat.vsize, WorkingSet = procFsStat.rss * Environment.SystemPageSize, SessionId = procFsStat.session, // We don't currently fill in the other values. // A few of these could probably be filled in from getrusage, // but only for the current process or its children, not for // arbitrary other processes. }; // Then read through /proc/pid/task/ to find each thread in the process... string tasksDir = Interop.procfs.GetTaskDirectoryPathForProcess(pid); try { foreach (string taskDir in Directory.EnumerateDirectories(tasksDir)) { // ...and read its associated /proc/pid/task/tid/stat file to create a ThreadInfo string dirName = Path.GetFileName(taskDir); int tid; Interop.procfs.ParsedStat stat; if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out tid) && Interop.procfs.TryReadStatFile(pid, tid, out stat, reusableReader)) { unsafe { pi._threadInfoList.Add(new ThreadInfo() { _processId = pid, _threadId = (ulong)tid, _basePriority = pi.BasePriority, _currentPriority = (int)stat.nice, _startAddress = IntPtr.Zero, _threadState = ProcFsStateToThreadState(stat.state), _threadWaitReason = ThreadWaitReason.Unknown }); } } } } catch (IOException) { // Between the time that we get an ID and the time that we try to read the associated // directories and files in procfs, the process could be gone. } // Finally return what we've built up return pi; } // ---------------------------------- // ---- Unix PAL layer ends here ---- // ---------------------------------- /// <summary>Enumerates the IDs of all processes on the current machine.</summary> internal static IEnumerable<int> EnumerateProcessIds() { // Parse /proc for any directory that's named with a number. Each such // directory represents a process. foreach (string procDir in Directory.EnumerateDirectories(Interop.procfs.RootPath)) { string dirName = Path.GetFileName(procDir); int pid; if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out pid)) { Debug.Assert(pid >= 0); yield return pid; } } } /// <summary>Gets a ThreadState to represent the value returned from the status field of /proc/pid/stat.</summary> /// <param name="c">The status field value.</param> /// <returns></returns> private static ThreadState ProcFsStateToThreadState(char c) { switch (c) { case 'R': // Running return ThreadState.Running; case 'D': // Waiting on disk case 'P': // Parked case 'S': // Sleeping in a wait case 't': // Tracing/debugging case 'T': // Stopped on a signal return ThreadState.Wait; case 'x': // dead case 'X': // Dead case 'Z': // Zombie return ThreadState.Terminated; case 'W': // Paging or waking case 'K': // Wakekill return ThreadState.Transition; default: Debug.Fail($"Unexpected status character: {c}"); return ThreadState.Unknown; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Internal; using Orleans.Runtime; using Orleans.Runtime.Messaging; namespace Orleans.Messaging { /// <summary> /// The GatewayManager class holds the list of known gateways, as well as maintaining the list of "dead" gateways. /// /// The known list can come from one of two places: the full list may appear in the client configuration object, or /// the config object may contain an IGatewayListProvider delegate. If both appear, then the delegate takes priority. /// </summary> internal class GatewayManager : IDisposable { private readonly object lockable = new object(); private readonly Dictionary<SiloAddress, DateTime> knownDead = new Dictionary<SiloAddress, DateTime>(); private readonly Dictionary<SiloAddress, DateTime> knownMasked = new Dictionary<SiloAddress, DateTime>(); private readonly IGatewayListProvider gatewayListProvider; private readonly ILogger logger; private readonly ConnectionManager connectionManager; private readonly GatewayOptions gatewayOptions; private AsyncTaskSafeTimer gatewayRefreshTimer; private List<SiloAddress> cachedLiveGateways; private HashSet<SiloAddress> cachedLiveGatewaysSet; private List<SiloAddress> knownGateways; private DateTime lastRefreshTime; private int roundRobinCounter; private bool gatewayRefreshCallInitiated; private bool gatewayListProviderInitialized; private readonly ILogger<SafeTimer> timerLogger; public GatewayManager( IOptions<GatewayOptions> gatewayOptions, IGatewayListProvider gatewayListProvider, ILoggerFactory loggerFactory, ConnectionManager connectionManager) { this.gatewayOptions = gatewayOptions.Value; this.logger = loggerFactory.CreateLogger<GatewayManager>(); this.connectionManager = connectionManager; this.gatewayListProvider = gatewayListProvider; this.timerLogger = loggerFactory.CreateLogger<SafeTimer>(); } public async Task StartAsync(CancellationToken cancellationToken) { if (!gatewayListProviderInitialized) { await this.gatewayListProvider.InitializeGatewayListProvider(); gatewayListProviderInitialized = true; } this.gatewayRefreshTimer = new AsyncTaskSafeTimer( this.timerLogger, RefreshSnapshotLiveGateways_TimerCallback, null, this.gatewayOptions.GatewayListRefreshPeriod, this.gatewayOptions.GatewayListRefreshPeriod); var knownGateways = await this.gatewayListProvider.GetGateways(); if (knownGateways.Count == 0) { var err = $"Could not find any gateway in {this.gatewayListProvider.GetType().FullName}. Orleans client cannot initialize."; this.logger.LogError((int)ErrorCode.GatewayManager_NoGateways, err); throw new SiloUnavailableException(err); } this.logger.LogInformation( (int)ErrorCode.GatewayManager_FoundKnownGateways, "Found {GatewayCount} gateways: {Gateways}", knownGateways.Count, Utils.EnumerableToString(knownGateways)); this.roundRobinCounter = this.gatewayOptions.PreferedGatewayIndex >= 0 ? this.gatewayOptions.PreferedGatewayIndex : ThreadSafeRandom.Next(knownGateways.Count); this.knownGateways = this.cachedLiveGateways = knownGateways.Select(gw => gw.ToGatewayAddress()).ToList(); this.cachedLiveGatewaysSet = new HashSet<SiloAddress>(cachedLiveGateways); this.lastRefreshTime = DateTime.UtcNow; } public void Stop() { if (gatewayRefreshTimer != null) { Utils.SafeExecute(gatewayRefreshTimer.Dispose, logger); } gatewayRefreshTimer = null; } public void MarkAsDead(SiloAddress gateway) { lock (lockable) { knownDead[gateway] = DateTime.UtcNow; var copy = new List<SiloAddress>(cachedLiveGateways); copy.Remove(gateway); // swap the reference, don't mutate cachedLiveGateways, so we can access cachedLiveGateways without the lock. cachedLiveGateways = copy; cachedLiveGatewaysSet = new HashSet<SiloAddress>(cachedLiveGateways); } } public void MarkAsUnavailableForSend(SiloAddress gateway) { lock (lockable) { knownMasked[gateway] = DateTime.UtcNow; var copy = new List<SiloAddress>(cachedLiveGateways); copy.Remove(gateway); // swap the reference, don't mutate cachedLiveGateways, so we can access cachedLiveGateways without the lock. cachedLiveGateways = copy; cachedLiveGatewaysSet = new HashSet<SiloAddress>(cachedLiveGateways); } } public override string ToString() { var sb = new StringBuilder(); sb.Append("GatewayManager: "); lock (lockable) { if (cachedLiveGateways != null) { sb.Append(cachedLiveGateways.Count); sb.Append(" cachedLiveGateways, "); } if (knownDead != null) { sb.Append(knownDead.Count); sb.Append(" known dead gateways."); } } return sb.ToString(); } /// <summary> /// Selects a gateway to use for a new bucket. /// /// Note that if a list provider delegate was given, the delegate is invoked every time this method is called. /// This method performs caching to avoid hammering the ultimate data source. /// /// This implementation does a simple round robin selection. It assumes that the gateway list from the provider /// is in the same order every time. /// </summary> /// <returns></returns> public SiloAddress GetLiveGateway() { List<SiloAddress> live = GetLiveGateways(); int count = live.Count; if (count > 0) { lock (lockable) { // Round-robin through the known gateways and take the next live one, starting from where we last left off roundRobinCounter = (roundRobinCounter + 1) % count; return live[roundRobinCounter]; } } // If we drop through, then all of the known gateways are presumed dead return null; } public List<SiloAddress> GetLiveGateways() { // Never takes a lock and returns the cachedLiveGateways list quickly without any operation. // Asynchronously starts gateway refresh only when it is empty. if (cachedLiveGateways.Count == 0) { ExpediteUpdateLiveGatewaysSnapshot(); if (knownGateways.Count > 0) { lock (this.lockable) { if (cachedLiveGateways.Count == 0 && knownGateways.Count > 0) { this.logger.LogWarning("All known gateways have been marked dead locally. Expediting gateway refresh and resetting all gateways to live status."); cachedLiveGateways = knownGateways; cachedLiveGatewaysSet = new HashSet<SiloAddress>(knownGateways); } } } } return cachedLiveGateways; } public bool IsGatewayAvailable(SiloAddress siloAddress) { return cachedLiveGatewaysSet.Contains(siloAddress); } internal void ExpediteUpdateLiveGatewaysSnapshot() { // If there is already an expedited refresh call in place, don't call again, until the previous one is finished. // We don't want to issue too many Gateway refresh calls. if (gatewayListProvider == null || gatewayRefreshCallInitiated) return; // Initiate gateway list refresh asynchronously. The Refresh timer will keep ticking regardless. // We don't want to block the client with synchronously Refresh call. // Client's call will fail with "No Gateways found" but we will try to refresh the list quickly. gatewayRefreshCallInitiated = true; _ = Task.Run(async () => { try { await RefreshSnapshotLiveGateways_TimerCallback(null); gatewayRefreshCallInitiated = false; } catch { // Intentionally ignore any exceptions here. } }); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal async Task RefreshSnapshotLiveGateways_TimerCallback(object context) { try { if (gatewayListProvider is null) return; // the listProvider.GetGateways() is not under lock. var allGateways = await gatewayListProvider.GetGateways(); var refreshedGateways = allGateways.Select(gw => gw.ToGatewayAddress()).ToList(); if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("Discovered {GatewayCount} gateways: {Gateways}", refreshedGateways.Count, Utils.EnumerableToString(refreshedGateways)); } await UpdateLiveGatewaysSnapshot(refreshedGateways, gatewayListProvider.MaxStaleness); } catch (Exception exc) { logger.Error(ErrorCode.ProxyClient_GetGateways, "Exception occurred during RefreshSnapshotLiveGateways_TimerCallback -> listProvider.GetGateways()", exc); } } // This function is called asynchronously from gateway refresh timer. private async Task UpdateLiveGatewaysSnapshot(IEnumerable<SiloAddress> refreshedGateways, TimeSpan maxStaleness) { List<SiloAddress> connectionsToKeepAlive; // This is a short lock, protecting the access to knownDead, knownMasked and cachedLiveGateways. lock (lockable) { // now take whatever listProvider gave us and exclude those we think are dead. var live = new List<SiloAddress>(); var now = DateTime.UtcNow; this.knownGateways = refreshedGateways as List<SiloAddress> ?? refreshedGateways.ToList(); foreach (SiloAddress trial in knownGateways) { var address = trial.Generation == 0 ? trial : SiloAddress.New(trial.Endpoint, 0); // We consider a node to be dead if we recorded it is dead due to socket error // and it was recorded (diedAt) not too long ago (less than maxStaleness ago). // The latter is to cover the case when the Gateway provider returns an outdated list that does not yet reflect the actually recently died Gateway. // If it has passed more than maxStaleness - we assume maxStaleness is the upper bound on Gateway provider freshness. var isDead = false; if (knownDead.TryGetValue(address, out var diedAt)) { if (now.Subtract(diedAt) < maxStaleness) { isDead = true; } else { // Remove stale entries. knownDead.Remove(address); } } if (knownMasked.TryGetValue(address, out var maskedAt)) { if (now.Subtract(maskedAt) < maxStaleness) { isDead = true; } else { // Remove stale entries. knownMasked.Remove(address); } } if (!isDead) { live.Add(address); } } if (live.Count == 0) { logger.Warn( ErrorCode.GatewayManager_AllGatewaysDead, "All gateways have previously been marked as dead. Clearing the list of dead gateways to expedite reconnection."); live.AddRange(knownGateways); knownDead.Clear(); } // swap cachedLiveGateways pointer in one atomic operation cachedLiveGateways = live; cachedLiveGatewaysSet = new HashSet<SiloAddress>(live); DateTime prevRefresh = lastRefreshTime; lastRefreshTime = now; if (logger.IsEnabled(LogLevel.Information)) { logger.Info(ErrorCode.GatewayManager_FoundKnownGateways, "Refreshed the live gateway list. Found {0} gateways from gateway list provider: {1}. Picked only known live out of them. Now has {2} live gateways: {3}. Previous refresh time was = {4}", knownGateways.Count, Utils.EnumerableToString(knownGateways), cachedLiveGateways.Count, Utils.EnumerableToString(cachedLiveGateways), prevRefresh); } // Close connections to known dead connections, but keep the "masked" ones. // Client will not send any new request to the "masked" connections, but might still // receive responses connectionsToKeepAlive = new List<SiloAddress>(live); connectionsToKeepAlive.AddRange(knownMasked.Select(e => e.Key)); } await this.CloseEvictedGatewayConnections(connectionsToKeepAlive); } private async Task CloseEvictedGatewayConnections(List<SiloAddress> liveGateways) { if (this.connectionManager == null) return; var connectedGateways = this.connectionManager.GetConnectedAddresses(); foreach (var address in connectedGateways) { var isLiveGateway = false; foreach (var live in liveGateways) { if (live.Matches(address)) { isLiveGateway = true; break; } } if (!isLiveGateway) { if (logger.IsEnabled(LogLevel.Information)) { this.logger.LogInformation("Closing connection to {Endpoint} because it has been marked as dead", address); } await this.connectionManager.CloseAsync(address); } } } public void Dispose() { this.gatewayRefreshTimer?.Dispose(); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using Microsoft.Xna.Framework; namespace map { /// <summary> /// Implementation of "FOV using recursive shadowcasting - improved" as /// described on http://roguebasin.roguelikedevelopment.org/index.php?title=FOV_using_recursive_shadowcasting_-_improved /// /// The FOV code is contained in the region "FOV Algorithm". /// The method GetVisibleCells() is called to calculate the cells /// visible to the player by examing each octant sequantially. /// The generic list VisiblePoints contains the cells visible to the player. /// /// GetVisibleCells() is called everytime the player moves, and the event playerMoved /// is called when a successful move is made (the player moves into an empty cell) /// /// </summary> public class FOVRecurse { public Point MapSize { get; set; } public int[,] map { get; private set; } /// <summary> /// Radius of the player's circle of vision /// </summary> public int VisualRange { get; set; } /// <summary> /// List of points visible to the player /// </summary> public List<Point> VisiblePoints { get; private set; } // Cells the player can see private Point player; public Point Player { get { return player; } set { player = value; } } /// <summary> /// The octants which a player can see /// </summary> List<int> VisibleOctants = new List<int>() { 1, 2, 3, 4,5,6,7,8 }; public FOVRecurse() { MapSize = new Point(100, 100); map = new int[MapSize.X, MapSize.Y]; VisualRange = 5; } /// <summary> /// Move the player in the specified direction provided the cell is valid and empty /// </summary> /// <param name="pX">X offset</param> /// <param name="pY">Y Offset</param> public void movePlayer(int pX, int pY) { if (Point_Valid(player.X + pX, player.Y + pY) && Point_Get(player.X + pX, player.Y + pY) == 0) { player.Offset(pX, pY); GetVisibleCells(); playerMoved(); } } #region map point code /// <summary> /// Check if the provided coordinate is within the bounds of the mapp array /// </summary> /// <param name="pX"></param> /// <param name="pY"></param> /// <returns></returns> private bool Point_Valid(int pX, int pY) { return pX >= 0 & pX < map.GetLength(0) & pY >= 0 & pY < map.GetLength(1); } /// <summary> /// Get the value of the point at the specified location /// </summary> /// <param name="_x"></param> /// <param name="_y"></param> /// <returns>Cell value</returns> public int Point_Get(int _x, int _y) { return map[_x, _y]; } /// <summary> /// Set the map point to the specified value /// </summary> /// <param name="_x"></param> /// <param name="_y"></param> /// <param name="_val"></param> public void Point_Set(int _x, int _y, int _val) { if (Point_Valid(_x, _y)) map[_x, _y] = _val; } #endregion #region FOV algorithm // Octant data // // \ 1 | 2 / // 8 \ | / 3 // -----+----- // 7 / | \ 4 // / 6 | 5 \ // // 1 = NNW, 2 =NNE, 3=ENE, 4=ESE, 5=SSE, 6=SSW, 7=WSW, 8 = WNW /// <summary> /// Start here: go through all the octants which surround the player to /// determine which open cells are visible /// </summary> public void GetVisibleCells() { VisiblePoints = new List<Point>(); foreach (int o in VisibleOctants) ScanOctant(1, o, 1.0, 0.0); } /// <summary> /// Examine the provided octant and calculate the visible cells within it. /// </summary> /// <param name="pDepth">Depth of the scan</param> /// <param name="pOctant">Octant being examined</param> /// <param name="pStartSlope">Start slope of the octant</param> /// <param name="pEndSlope">End slope of the octance</param> protected void ScanOctant(int pDepth, int pOctant, double pStartSlope, double pEndSlope) { int visrange2 = VisualRange * VisualRange; int x = 0; int y = 0; switch (pOctant) { case 1: //nnw y = player.Y - pDepth; if (y < 0) return; x = player.X - Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth))); if (x < 0) x = 0; while (GetSlope(x, y, player.X, player.Y, false) >= pEndSlope) { if (GetVisDistance(x, y, player.X, player.Y) <= visrange2) { if (map[x, y] == 1) //current cell blocked { if (x - 1 >= 0 && map[x - 1, y] == 0) //prior cell within range AND open... //...incremenet the depth, adjust the endslope and recurse ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x - 0.5, y + 0.5, player.X, player.Y, false)); } else { if (x - 1 >= 0 && map[x - 1, y] == 1) //prior cell within range AND open... //..adjust the startslope pStartSlope = GetSlope(x - 0.5, y - 0.5, player.X, player.Y, false); VisiblePoints.Add(new Point(x, y)); } } x++; } x--; break; case 2: //nne y = player.Y - pDepth; if (y < 0) return; x = player.X + Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth))); if (x >= map.GetLength(0)) x = map.GetLength(0) - 1; while (GetSlope(x, y, player.X, player.Y, false) <= pEndSlope) { if (GetVisDistance(x, y, player.X, player.Y) <= visrange2) { if (map[x, y] == 1) { if (x + 1 < map.GetLength(0) && map[x + 1, y] == 0) ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x + 0.5, y + 0.5, player.X, player.Y, false)); } else { if (x + 1 < map.GetLength(0) && map[x + 1, y] == 1) pStartSlope = -GetSlope(x + 0.5, y - 0.5, player.X, player.Y, false); VisiblePoints.Add(new Point(x, y)); } } x--; } x++; break; case 3: x = player.X + pDepth; if (x >= map.GetLength(0)) return; y = player.Y - Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth))); if (y < 0) y = 0; while (GetSlope(x, y, player.X, player.Y, true) <= pEndSlope) { if (GetVisDistance(x, y, player.X, player.Y) <= visrange2) { if (map[x, y] == 1) { if (y - 1 >= 0 && map[x, y - 1] == 0) ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x - 0.5, y - 0.5, player.X, player.Y, true)); } else { if (y - 1 >= 0 && map[x, y - 1] == 1) pStartSlope = -GetSlope(x + 0.5, y - 0.5, player.X, player.Y, true); VisiblePoints.Add(new Point(x, y)); } } y++; } y--; break; case 4: x = player.X + pDepth; if (x >= map.GetLength(0)) return; y = player.Y + Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth))); if (y >= map.GetLength(1)) y = map.GetLength(1) - 1; while (GetSlope(x, y, player.X, player.Y, true) >= pEndSlope) { if (GetVisDistance(x, y, player.X, player.Y) <= visrange2) { if (map[x, y] == 1) { if (y + 1 < map.GetLength(1)&& map[x, y + 1] == 0) ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x - 0.5, y + 0.5, player.X, player.Y, true)); } else { if (y + 1 < map.GetLength(1) && map[x, y + 1] == 1) pStartSlope = GetSlope(x + 0.5, y + 0.5, player.X, player.Y, true); VisiblePoints.Add(new Point(x, y)); } } y--; } y++; break; case 5: y = player.Y + pDepth; if (y >= map.GetLength(1)) return; x = player.X + Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth))); if (x >= map.GetLength(0)) x = map.GetLength(0) - 1; while (GetSlope(x, y, player.X, player.Y, false) >= pEndSlope) { if (GetVisDistance(x, y, player.X, player.Y) <= visrange2) { if (map[x, y] == 1) { if (x + 1 < map.GetLength(1) && map[x+1, y] == 0) ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x + 0.5, y - 0.5, player.X, player.Y, false)); } else { if (x + 1 < map.GetLength(1) && map[x + 1, y] == 1) pStartSlope = GetSlope(x + 0.5, y + 0.5, player.X, player.Y, false); VisiblePoints.Add(new Point(x, y)); } } x--; } x++; break; case 6: y = player.Y + pDepth; if (y >= map.GetLength(1)) return; x = player.X - Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth))); if (x < 0) x = 0; while (GetSlope(x, y, player.X, player.Y, false) <= pEndSlope) { if (GetVisDistance(x, y, player.X, player.Y) <= visrange2) { if (map[x, y] == 1) { if (x - 1 >= 0 && map[x - 1, y] == 0) ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x - 0.5, y - 0.5, player.X, player.Y, false)); } else { if (x - 1 >= 0 && map[x - 1, y] == 1) pStartSlope = -GetSlope(x - 0.5, y + 0.5, player.X, player.Y, false); VisiblePoints.Add(new Point(x, y)); } } x++; } x--; break; case 7: x = player.X - pDepth; if (x < 0) return; y = player.Y + Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth))); if (y >= map.GetLength(1)) y = map.GetLength(1) - 1; while (GetSlope(x, y, player.X, player.Y, true) <= pEndSlope) { if (GetVisDistance(x, y, player.X, player.Y) <= visrange2) { if (map[x, y] == 1) { if (y + 1 < map.GetLength(1) && map[x, y+1] == 0) ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x + 0.5, y + 0.5, player.X, player.Y, true)); } else { if (y + 1 < map.GetLength(1) && map[x, y + 1] == 1) pStartSlope = -GetSlope(x - 0.5, y + 0.5, player.X, player.Y, true); VisiblePoints.Add(new Point(x, y)); } } y--; } y++; break; case 8: //wnw x = player.X - pDepth; if (x < 0) return; y = player.Y - Convert.ToInt32((pStartSlope * Convert.ToDouble(pDepth))); if (y < 0) y = 0; while (GetSlope(x, y, player.X, player.Y, true) >= pEndSlope) { if (GetVisDistance(x, y, player.X, player.Y) <= visrange2) { if (map[x, y] == 1) { if (y - 1 >=0 && map[x, y - 1] == 0) ScanOctant(pDepth + 1, pOctant, pStartSlope, GetSlope(x + 0.5, y - 0.5, player.X, player.Y, true)); } else { if (y - 1 >= 0 && map[x, y - 1] == 1) pStartSlope = GetSlope(x - 0.5, y - 0.5, player.X, player.Y, true); VisiblePoints.Add(new Point(x, y)); } } y++; } y--; break; } if (x < 0) x = 0; else if (x >= map.GetLength(0)) x = map.GetLength(0) - 1; if (y < 0) y = 0; else if (y >= map.GetLength(1)) y = map.GetLength(1) - 1; if (pDepth < VisualRange & map[x, y] == 0) ScanOctant(pDepth + 1, pOctant, pStartSlope, pEndSlope); } /// <summary> /// Get the gradient of the slope formed by the two points /// </summary> /// <param name="pX1"></param> /// <param name="pY1"></param> /// <param name="pX2"></param> /// <param name="pY2"></param> /// <param name="pInvert">Invert slope</param> /// <returns></returns> private double GetSlope(double pX1, double pY1, double pX2, double pY2, bool pInvert) { if (pInvert) return (pY1 - pY2) / (pX1 - pX2); else return (pX1 - pX2) / (pY1 - pY2); } /// <summary> /// Calculate the distance between the two points /// </summary> /// <param name="pX1"></param> /// <param name="pY1"></param> /// <param name="pX2"></param> /// <param name="pY2"></param> /// <returns>Distance</returns> private int GetVisDistance(int pX1, int pY1, int pX2, int pY2) { return ((pX1 - pX2) * (pX1 - pX2)) + ((pY1 - pY2) * (pY1 - pY2)); } #endregion //event raised when a player has successfully moved public delegate void moveDelegate(); public event moveDelegate playerMoved; } }
//------------------------------------------------------------------------------ // <copyright file="ToolStripProgressBar.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System; using System.Windows.Forms; using System.ComponentModel; using System.Drawing; using System.Security; using System.Security.Permissions; /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar"]/*' /> [DefaultProperty("Value")] public class ToolStripProgressBar : ToolStripControlHost { internal static readonly object EventRightToLeftLayoutChanged = new object(); /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.ToolStripProgressBar"]/*' /> public ToolStripProgressBar() : base(CreateControlInstance()) { } public ToolStripProgressBar(string name) : this() { this.Name = name; } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.ProgressBar"]/*' /> /// <devdoc> /// Create a strongly typed accessor for the class /// </devdoc> /// <value></value> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ProgressBar ProgressBar { get { return this.Control as ProgressBar; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public override Image BackgroundImage { get { return base.BackgroundImage; } set { base.BackgroundImage = value; } } [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public override ImageLayout BackgroundImageLayout { get { return base.BackgroundImageLayout; } set { base.BackgroundImageLayout = value; } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.DefaultSize"]/*' /> /// <devdoc> /// Specify what size you want the item to start out at /// </devdoc> /// <value></value> protected override System.Drawing.Size DefaultSize { get { return new Size(100,15); } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.DefaultMargin"]/*' /> /// <devdoc> /// Specify how far from the edges you want to be /// </devdoc> /// <value></value> protected internal override Padding DefaultMargin { get { if (this.Owner != null && this.Owner is StatusStrip) { return new Padding(1, 3, 1, 3); } else { return new Padding(1, 2, 1, 1); } } } [ DefaultValue(100), SRCategory(SR.CatBehavior), SRDescription(SR.ProgressBarMarqueeAnimationSpeed) ] public int MarqueeAnimationSpeed { get { return ProgressBar.MarqueeAnimationSpeed; } set { ProgressBar.MarqueeAnimationSpeed = value; } } [ DefaultValue(100), SRCategory(SR.CatBehavior), RefreshProperties(RefreshProperties.Repaint), SRDescription(SR.ProgressBarMaximumDescr) ] public int Maximum { get { return ProgressBar.Maximum; } set { ProgressBar.Maximum = value; } } [ DefaultValue(0), SRCategory(SR.CatBehavior), RefreshProperties(RefreshProperties.Repaint), SRDescription(SR.ProgressBarMinimumDescr) ] public int Minimum { get { return ProgressBar.Minimum; } set { ProgressBar.Minimum = value; } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.RightToLeftLayout"]/*' /> /// <devdoc> /// This is used for international applications where the language /// is written from RightToLeft. When this property is true, // and the RightToLeft is true, mirroring will be turned on on the form, and /// control placement and text will be from right to left. /// </devdoc> [ SRCategory(SR.CatAppearance), Localizable(true), DefaultValue(false), SRDescription(SR.ControlRightToLeftLayoutDescr) ] public virtual bool RightToLeftLayout { get { return ProgressBar.RightToLeftLayout; } set { ProgressBar.RightToLeftLayout = value; } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.Step"]/*' /> /// <devdoc> /// Wrap some commonly used properties /// </devdoc> /// <value></value> [ DefaultValue(10), SRCategory(SR.CatBehavior), SRDescription(SR.ProgressBarStepDescr) ] public int Step { get { return ProgressBar.Step; } set { ProgressBar.Step = value; } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.Style"]/*' /> /// <devdoc> /// Wrap some commonly used properties /// </devdoc> /// <value></value> [ DefaultValue(ProgressBarStyle.Blocks), SRCategory(SR.CatBehavior), SRDescription(SR.ProgressBarStyleDescr) ] public ProgressBarStyle Style { get { return ProgressBar.Style; } set { ProgressBar.Style = value; } } /// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.Text"]/*' /> /// <devdoc> /// Hide the property. /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public override string Text { get { return Control.Text; } set { Control.Text = value; } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.Value"]/*' /> /// <devdoc> /// Wrap some commonly used properties /// </devdoc> /// <value></value> [ DefaultValue(0), SRCategory(SR.CatBehavior), Bindable(true), SRDescription(SR.ProgressBarValueDescr) ] public int Value { get { return ProgressBar.Value; } set { ProgressBar.Value = value; } } private static Control CreateControlInstance() { ProgressBar progressBar = new ProgressBar(); progressBar.Size = new Size(100,15); return progressBar; } private void HandleRightToLeftLayoutChanged(object sender, EventArgs e) { OnRightToLeftLayoutChanged(e); } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.OnRightToLeftLayoutChanged"]/*' /> protected virtual void OnRightToLeftLayoutChanged(EventArgs e) { RaiseEvent(EventRightToLeftLayoutChanged, e); } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.OnSubscribeControlEvents"]/*' /> protected override void OnSubscribeControlEvents(Control control) { ProgressBar bar = control as ProgressBar; if (bar != null) { // Please keep this alphabetized and in [....] with Unsubscribe // bar.RightToLeftLayoutChanged += new EventHandler(HandleRightToLeftLayoutChanged); } base.OnSubscribeControlEvents(control); } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.OnUnsubscribeControlEvents"]/*' /> protected override void OnUnsubscribeControlEvents(Control control) { ProgressBar bar = control as ProgressBar; if (bar != null) { // Please keep this alphabetized and in [....] with Subscribe // bar.RightToLeftLayoutChanged -= new EventHandler(HandleRightToLeftLayoutChanged); } base.OnUnsubscribeControlEvents(control); } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.Paint"]/*' /> /// <devdoc> /// <para>Hide the event.</para> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] new public event KeyEventHandler KeyDown { add { base.KeyDown += value; } remove { base.KeyDown -= value; } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.Paint"]/*' /> /// <devdoc> /// <para>Hide the event.</para> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] new public event KeyPressEventHandler KeyPress { add { base.KeyPress += value; } remove { base.KeyPress -= value; } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.Paint"]/*' /> /// <devdoc> /// <para>Hide the event.</para> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] new public event KeyEventHandler KeyUp { add { base.KeyUp += value; } remove { base.KeyUp -= value; } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.Paint"]/*' /> /// <devdoc> /// <para>Hide the event.</para> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] new public event EventHandler LocationChanged { add { base.LocationChanged += value; } remove { base.LocationChanged -= value; } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.Paint"]/*' /> /// <devdoc> /// <para>Hide the event.</para> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] new public event EventHandler OwnerChanged { add { base.OwnerChanged += value; } remove { base.OwnerChanged -= value; } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.RightToLeftLayoutChanged"]/*' /> [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnRightToLeftLayoutChangedDescr)] public event EventHandler RightToLeftLayoutChanged { add { Events.AddHandler(EventRightToLeftLayoutChanged, value); } remove { Events.RemoveHandler(EventRightToLeftLayoutChanged, value); } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.Paint"]/*' /> /// <devdoc> /// <para>Hide the event.</para> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] new public event EventHandler TextChanged { add { base.TextChanged += value; } remove { base.TextChanged -= value; } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.Paint"]/*' /> /// <devdoc> /// <para>Hide the event.</para> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] new public event EventHandler Validated { add { base.Validated += value; } remove { base.Validated -= value; } } /// <include file='doc\ToolStripProgressBar.uex' path='docs/doc[@for="ToolStripProgressBar.Paint"]/*' /> /// <devdoc> /// <para>Hide the event.</para> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never) ] new public event CancelEventHandler Validating { add { base.Validating += value; } remove { base.Validating -= value; } } public void Increment(int value) { ProgressBar.Increment(value); } public void PerformStep() { ProgressBar.PerformStep(); } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt #nullable enable using System; using System.Collections.Generic; using System.IO; using System.Reflection; using NUnit.Framework.Constraints; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Execution; namespace NUnit.Framework { /// <summary> /// Provide the context information of the current test. /// This is an adapter for the internal ExecutionContext /// class, hiding the internals from the user test. /// </summary> public class TestContext { private readonly TestExecutionContext _testExecutionContext; private TestAdapter? _test; private ResultAdapter? _result; #region Constructor /// <summary> /// Construct a TestContext for an ExecutionContext /// </summary> /// <param name="testExecutionContext">The ExecutionContext to adapt</param> public TestContext(TestExecutionContext testExecutionContext) { _testExecutionContext = testExecutionContext; } #endregion #region Properties /// <summary> /// Get the current test context. This is created /// as needed. The user may save the context for /// use within a test, but it should not be used /// outside the test for which it is created. /// </summary> public static TestContext CurrentContext { get { return new TestContext(TestExecutionContext.CurrentContext); } } /// <summary> /// Gets a TextWriter that will send output to the current test result. /// </summary> public static TextWriter Out { get { return TestExecutionContext.CurrentContext.OutWriter; } } /// <summary> /// Gets a TextWriter that will send output directly to Console.Error /// </summary> public static TextWriter Error = new EventListenerTextWriter("Error", Console.Error); /// <summary> /// Gets a TextWriter for use in displaying immediate progress messages /// </summary> public static readonly TextWriter Progress = new EventListenerTextWriter("Progress", Console.Error); /// <summary> /// TestParameters object holds parameters for the test run, if any are specified /// </summary> public static readonly TestParameters Parameters = new TestParameters(); /// <summary> /// Static DefaultWorkDirectory is now used as the source /// of the public instance property WorkDirectory. This is /// a bit odd but necessary to avoid breaking user tests. /// </summary> internal static string? DefaultWorkDirectory; /// <summary> /// Get a representation of the current test. /// </summary> public TestAdapter Test { get { return _test ?? (_test = new TestAdapter(_testExecutionContext.CurrentTest)); } } /// <summary> /// Gets a Representation of the TestResult for the current test. /// </summary> public ResultAdapter Result { get { return _result ?? (_result = new ResultAdapter(_testExecutionContext.CurrentResult)); } } /// <summary> /// Gets the unique name of the Worker that is executing this test. /// </summary> public string? WorkerId { get { return _testExecutionContext.TestWorker?.Name; } } /// <summary> /// Gets the directory containing the current test assembly. /// </summary> public string TestDirectory { get { Assembly? assembly = _testExecutionContext?.CurrentTest?.TypeInfo?.Assembly; if (assembly != null) return AssemblyHelper.GetDirectoryName(assembly); // Test is null, we may be loading tests rather than executing. // Assume that calling assembly is the test assembly. return AssemblyHelper.GetDirectoryName(Assembly.GetCallingAssembly()); } } /// <summary> /// Gets the directory to be used for outputting files created /// by this test run. /// </summary> public string WorkDirectory => DefaultWorkDirectory ?? throw new InvalidOperationException("TestContext.WorkDirectory must not be accessed before DefaultTestAssemblyBuilder.Build runs."); /// <summary> /// Gets the random generator. /// </summary> /// <value> /// The random generator. /// </value> public Randomizer Random { get { return _testExecutionContext.RandomGenerator; } } /// <summary> /// Gets the number of assertions executed /// up to this point in the test. /// </summary> public int AssertCount { get { return _testExecutionContext.AssertCount; } } /// <summary> /// Get the number of times the current Test has been repeated /// when using the <see cref="RetryAttribute"/> or <see cref="RepeatAttribute"/>. /// </summary> public int CurrentRepeatCount { get { return _testExecutionContext.CurrentRepeatCount; } } #endregion #region Static Methods /// <summary>Write the string representation of a boolean value to the current result</summary> public static void Write(bool value) { Out.Write(value); } /// <summary>Write a char to the current result</summary> public static void Write(char value) { Out.Write(value); } /// <summary>Write a char array to the current result</summary> public static void Write(char[]? value) { Out.Write(value); } /// <summary>Write the string representation of a double to the current result</summary> public static void Write(double value) { Out.Write(value); } /// <summary>Write the string representation of an Int32 value to the current result</summary> public static void Write(Int32 value) { Out.Write(value); } /// <summary>Write the string representation of an Int64 value to the current result</summary> public static void Write(Int64 value) { Out.Write(value); } /// <summary>Write the string representation of a decimal value to the current result</summary> public static void Write(decimal value) { Out.Write(value); } /// <summary>Write the string representation of an object to the current result</summary> public static void Write(object? value) { Out.Write(value); } /// <summary>Write the string representation of a Single value to the current result</summary> public static void Write(Single value) { Out.Write(value); } /// <summary>Write a string to the current result</summary> public static void Write(string? value) { Out.Write(value); } /// <summary>Write the string representation of a UInt32 value to the current result</summary> [CLSCompliant(false)] public static void Write(UInt32 value) { Out.Write(value); } /// <summary>Write the string representation of a UInt64 value to the current result</summary> [CLSCompliant(false)] public static void Write(UInt64 value) { Out.Write(value); } /// <summary>Write a formatted string to the current result</summary> public static void Write(string format, object? arg1) { Out.Write(format, arg1); } /// <summary>Write a formatted string to the current result</summary> public static void Write(string format, object? arg1, object? arg2) { Out.Write(format, arg1, arg2); } /// <summary>Write a formatted string to the current result</summary> public static void Write(string format, object? arg1, object? arg2, object? arg3) { Out.Write(format, arg1, arg2, arg3); } /// <summary>Write a formatted string to the current result</summary> public static void Write(string format, params object?[] args) { Out.Write(format, args); } /// <summary>Write a line terminator to the current result</summary> public static void WriteLine() { Out.WriteLine(); } /// <summary>Write the string representation of a boolean value to the current result followed by a line terminator</summary> public static void WriteLine(bool value) { Out.WriteLine(value); } /// <summary>Write a char to the current result followed by a line terminator</summary> public static void WriteLine(char value) { Out.WriteLine(value); } /// <summary>Write a char array to the current result followed by a line terminator</summary> public static void WriteLine(char[]? value) { Out.WriteLine(value); } /// <summary>Write the string representation of a double to the current result followed by a line terminator</summary> public static void WriteLine(double value) { Out.WriteLine(value); } /// <summary>Write the string representation of an Int32 value to the current result followed by a line terminator</summary> public static void WriteLine(Int32 value) { Out.WriteLine(value); } /// <summary>Write the string representation of an Int64 value to the current result followed by a line terminator</summary> public static void WriteLine(Int64 value) { Out.WriteLine(value); } /// <summary>Write the string representation of a decimal value to the current result followed by a line terminator</summary> public static void WriteLine(decimal value) { Out.WriteLine(value); } /// <summary>Write the string representation of an object to the current result followed by a line terminator</summary> public static void WriteLine(object? value) { Out.WriteLine(value); } /// <summary>Write the string representation of a Single value to the current result followed by a line terminator</summary> public static void WriteLine(Single value) { Out.WriteLine(value); } /// <summary>Write a string to the current result followed by a line terminator</summary> public static void WriteLine(string? value) { Out.WriteLine(value); } /// <summary>Write the string representation of a UInt32 value to the current result followed by a line terminator</summary> [CLSCompliant(false)] public static void WriteLine(UInt32 value) { Out.WriteLine(value); } /// <summary>Write the string representation of a UInt64 value to the current result followed by a line terminator</summary> [CLSCompliant(false)] public static void WriteLine(UInt64 value) { Out.WriteLine(value); } /// <summary>Write a formatted string to the current result followed by a line terminator</summary> public static void WriteLine(string format, object? arg1) { Out.WriteLine(format, arg1); } /// <summary>Write a formatted string to the current result followed by a line terminator</summary> public static void WriteLine(string format, object? arg1, object? arg2) { Out.WriteLine(format, arg1, arg2); } /// <summary>Write a formatted string to the current result followed by a line terminator</summary> public static void WriteLine(string format, object? arg1, object? arg2, object? arg3) { Out.WriteLine(format, arg1, arg2, arg3); } /// <summary>Write a formatted string to the current result followed by a line terminator</summary> public static void WriteLine(string format, params object?[] args) { Out.WriteLine(format, args); } /// <summary> /// This method adds the a new ValueFormatterFactory to the /// chain of responsibility used for formatting values in messages. /// The scope of the change is the current TestContext. /// </summary> /// <param name="formatterFactory">The factory delegate</param> public static void AddFormatter(ValueFormatterFactory formatterFactory) { TestExecutionContext.CurrentContext.AddFormatter(formatterFactory); } /// <summary> /// Attach a file to the current test result /// </summary> /// <param name="filePath">Relative or absolute file path to attachment</param> /// <param name="description">Optional description of attachment</param> public static void AddTestAttachment(string filePath, string? description = null) { Guard.ArgumentNotNull(filePath, nameof(filePath)); Guard.ArgumentValid(filePath.IndexOfAny(Path.GetInvalidPathChars()) == -1, $"Test attachment file path contains invalid path characters. {filePath}", nameof(filePath)); if (!Path.IsPathRooted(filePath)) filePath = Path.Combine(TestContext.CurrentContext.WorkDirectory, filePath); if (!File.Exists(filePath)) throw new FileNotFoundException("Test attachment file path could not be found.", filePath); var result = TestExecutionContext.CurrentContext.CurrentResult; result.AddTestAttachment(new TestAttachment(filePath, description)); } /// <summary> /// This method provides a simplified way to add a ValueFormatter /// delegate to the chain of responsibility, creating the factory /// delegate internally. It is useful when the Type of the object /// is the only criterion for selection of the formatter, since /// it can be used without getting involved with a compound function. /// </summary> /// <typeparam name="TSupported">The type supported by this formatter</typeparam> /// <param name="formatter">The ValueFormatter delegate</param> public static void AddFormatter<TSupported>(ValueFormatter formatter) { AddFormatter(next => val => (val is TSupported) ? formatter(val) : next(val)); } #endregion #region Nested TestAdapter Class /// <summary> /// TestAdapter adapts a Test for consumption by /// the user test code. /// </summary> public class TestAdapter { private readonly Test _test; #region Constructor /// <summary> /// Construct a TestAdapter for a Test /// </summary> /// <param name="test">The Test to be adapted</param> public TestAdapter(Test test) { _test = test; } #endregion #region Properties /// <summary> /// Gets the unique Id of a test /// </summary> public String ID { get { return _test.Id; } } /// <summary> /// The name of the test, which may or may not be /// the same as the method name. /// </summary> public string Name { get { return _test.Name; } } /// <summary> /// The name of the method representing the test. /// </summary> public string? MethodName { get { return (_test as TestMethod)?.Method.Name; } } /// <summary> /// The FullName of the test /// </summary> public string FullName { get { return _test.FullName; } } /// <summary> /// The ClassName of the test /// </summary> public string? ClassName { get { return _test.ClassName; } } /// <summary> /// A shallow copy of the properties of the test. /// </summary> public PropertyBagAdapter Properties { get { return new PropertyBagAdapter(_test.Properties); } } /// <summary> /// The arguments to use in creating the test or empty array if none are required. /// </summary> public object?[] Arguments { get { return _test.Arguments; } } #endregion } #endregion #region Nested ResultAdapter Class /// <summary> /// ResultAdapter adapts a TestResult for consumption by /// the user test code. /// </summary> public class ResultAdapter { private readonly TestResult _result; #region Constructor /// <summary> /// Construct a ResultAdapter for a TestResult /// </summary> /// <param name="result">The TestResult to be adapted</param> public ResultAdapter(TestResult result) { _result = result; } #endregion #region Properties /// <summary> /// Gets a ResultState representing the outcome of the test /// up to this point in its execution. /// </summary> public ResultState Outcome { get { return _result.ResultState; } } /// <summary> /// Gets a list of the assertion results generated /// up to this point in the test. /// </summary> public IEnumerable<AssertionResult> Assertions { get { return _result.AssertionResults; } } /// <summary> /// Gets the message associated with a test /// failure or with not running the test /// </summary> public string? Message { get { return _result.Message; } } /// <summary> /// Gets any stack trace associated with an /// error or failure. /// </summary> public virtual string? StackTrace { get { return _result.StackTrace; } } /// <summary> /// Gets the number of test cases that failed /// when running the test and all its children. /// </summary> public int FailCount { get { return _result.FailCount; } } /// <summary> /// Gets the number of test cases that had warnings /// when running the test and all its children. /// </summary> public int WarningCount { get { return _result.WarningCount; } } /// <summary> /// Gets the number of test cases that passed /// when running the test and all its children. /// </summary> public int PassCount { get { return _result.PassCount; } } /// <summary> /// Gets the number of test cases that were skipped /// when running the test and all its children. /// </summary> public int SkipCount { get { return _result.SkipCount; } } /// <summary> /// Gets the number of test cases that were inconclusive /// when running the test and all its children. /// </summary> public int InconclusiveCount { get { return _result.InconclusiveCount; } } #endregion } #endregion #region Nested PropertyBagAdapter Class /// <summary> /// <see cref="PropertyBagAdapter"/> adapts an <see cref="IPropertyBag"/> /// for consumption by the user. /// </summary> public class PropertyBagAdapter { private readonly IPropertyBag _source; /// <summary> /// Construct a <see cref="PropertyBagAdapter"/> from a source /// <see cref="IPropertyBag"/>. /// </summary> public PropertyBagAdapter(IPropertyBag source) { _source = source; } /// <summary> /// Get the first property with the given <paramref name="key"/>, if it can be found, otherwise /// returns null. /// </summary> public object? Get(string key) { return _source.Get(key); } /// <summary> /// Indicates whether <paramref name="key"/> is found in this /// <see cref="PropertyBagAdapter"/>. /// </summary> public bool ContainsKey(string key) { return _source.ContainsKey(key); } /// <summary> /// Returns a collection of properties /// with the given <paramref name="key"/>. /// </summary> public IEnumerable<object> this[string key] { get { var list = new List<object>(); foreach(var item in _source[key]) { list.Add(item); } return list; } } /// <summary> /// Returns the count of elements with the given <paramref name="key"/>. /// </summary> public int Count(string key) { return _source[key].Count; } /// <summary> /// Returns a collection of the property keys. /// </summary> public ICollection<string> Keys { get { return _source.Keys; } } } #endregion } }
#region Copyright // // Nini Configuration Project. // // Copyright (C) 2014 Nicholas Omann. All rights reserved. // Copyright (C) 2006 Brent R. Matzelle. All rights reserved. // // This software is published under the terms of the MIT X11 license, a copy of // which has been included with this distribution in the LICENSE.txt file. // #endregion using System; using System.IO; using System.Xml; using Nini.Config; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Nini.Test.Config { [TestClass] public class ConfigSourceBaseTests { #region Private variables IConfig eventConfig = null; IConfigSource eventSource = null; int reloadedCount = 0; int savedCount = 0; string keyName = null; string keyValue = null; int keySetCount = 0; int keyRemovedCount = 0; #endregion #region Unit tests [TestMethod] public void Merge () { StringWriter textWriter = new StringWriter (); XmlTextWriter xmlWriter = NiniWriter (textWriter); WriteSection (xmlWriter, "Pets"); WriteKey (xmlWriter, "cat", "muffy"); WriteKey (xmlWriter, "dog", "rover"); WriteKey (xmlWriter, "bird", "tweety"); xmlWriter.WriteEndDocument (); StringReader reader = new StringReader (textWriter.ToString ()); XmlTextReader xmlReader = new XmlTextReader (reader); XmlConfigSource xmlSource = new XmlConfigSource (xmlReader); StringWriter writer = new StringWriter (); writer.WriteLine ("[People]"); writer.WriteLine (" woman = Jane"); writer.WriteLine (" man = John"); IniConfigSource iniSource = new IniConfigSource (new StringReader (writer.ToString ())); xmlSource.Merge (iniSource); IConfig config = xmlSource.Configs["Pets"]; Assert.AreEqual (3, config.GetKeys ().Length); Assert.AreEqual ("muffy", config.Get ("cat")); Assert.AreEqual ("rover", config.Get ("dog")); config = xmlSource.Configs["People"]; Assert.AreEqual (2, config.GetKeys ().Length); Assert.AreEqual ("Jane", config.Get ("woman")); Assert.AreEqual ("John", config.Get ("man")); } [ExpectedException (typeof (ArgumentException))] public void MergeItself () { StringWriter writer = new StringWriter (); writer.WriteLine ("[People]"); writer.WriteLine (" woman = Jane"); writer.WriteLine (" man = John"); IniConfigSource iniSource = new IniConfigSource (new StringReader (writer.ToString ())); iniSource.Merge (iniSource); // exception } [ExpectedException (typeof (ArgumentException))] public void MergeExisting () { StringWriter textWriter = new StringWriter (); XmlTextWriter xmlWriter = NiniWriter (textWriter); WriteSection (xmlWriter, "Pets"); WriteKey (xmlWriter, "cat", "muffy"); xmlWriter.WriteEndDocument (); StringReader reader = new StringReader (xmlWriter.ToString ()); XmlTextReader xmlReader = new XmlTextReader (reader); XmlConfigSource xmlSource = new XmlConfigSource (xmlReader); StringWriter writer = new StringWriter (); writer.WriteLine ("[People]"); writer.WriteLine (" woman = Jane"); IniConfigSource iniSource = new IniConfigSource (new StringReader (writer.ToString ())); xmlSource.Merge (iniSource); xmlSource.Merge (iniSource); // exception } [TestMethod] public void AutoSave () { string filePath = "AutoSaveTest.ini"; StreamWriter writer = new StreamWriter (filePath); writer.WriteLine ("; some comment"); writer.WriteLine ("[new section]"); writer.WriteLine (" dog = Rover"); writer.WriteLine (""); // empty line writer.WriteLine ("; a comment"); writer.WriteLine (" cat = Muffy"); writer.Close (); IniConfigSource source = new IniConfigSource (filePath); source.AutoSave = true; IConfig config = source.Configs["new section"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); config.Set ("dog", "Spots"); config.Set ("cat", "Misha"); Assert.AreEqual ("Spots", config.Get ("dog")); Assert.AreEqual ("Misha", config.Get ("cat")); source = new IniConfigSource (filePath); config = source.Configs["new section"]; Assert.AreEqual ("Spots", config.Get ("dog")); Assert.AreEqual ("Misha", config.Get ("cat")); File.Delete (filePath); } [TestMethod] public void AddConfig () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Test]"); writer.WriteLine (" bool 1 = TrUe"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig newConfig = source.AddConfig ("NewConfig"); newConfig.Set ("NewKey", "NewValue"); newConfig.Set ("AnotherKey", "AnotherValue"); IConfig config = source.Configs["NewConfig"]; Assert.AreEqual (2, config.GetKeys ().Length); Assert.AreEqual ("NewValue", config.Get ("NewKey")); Assert.AreEqual ("AnotherValue", config.Get ("AnotherKey")); } [TestMethod] public void ExpandText () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Test]"); writer.WriteLine (" author = Brent"); writer.WriteLine (" domain = ${protocol}://nini.sf.net/"); writer.WriteLine (" apache = Apache implements ${protocol}"); writer.WriteLine (" developer = author of Nini: ${author} !"); writer.WriteLine (" love = We love the ${protocol} protocol"); writer.WriteLine (" combination = ${author} likes ${protocol}"); writer.WriteLine (" fact = fact: ${apache}"); writer.WriteLine (" protocol = http"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); source.ExpandKeyValues (); IConfig config = source.Configs["Test"]; Assert.AreEqual ("http", config.Get ("protocol")); Assert.AreEqual ("fact: Apache implements http", config.Get ("fact")); Assert.AreEqual ("http://nini.sf.net/", config.Get ("domain")); Assert.AreEqual ("Apache implements http", config.Get ("apache")); Assert.AreEqual ("We love the http protocol", config.Get ("love")); Assert.AreEqual ("author of Nini: Brent !", config.Get ("developer")); Assert.AreEqual ("Brent likes http", config.Get ("combination")); } [TestMethod] public void ExpandTextOtherSection () { StringWriter writer = new StringWriter (); writer.WriteLine ("[web]"); writer.WriteLine (" apache = Apache implements ${protocol}"); writer.WriteLine (" protocol = http"); writer.WriteLine ("[server]"); writer.WriteLine (" domain = ${web|protocol}://nini.sf.net/"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); source.ExpandKeyValues (); IConfig config = source.Configs["web"]; Assert.AreEqual ("http", config.Get ("protocol")); Assert.AreEqual ("Apache implements http", config.Get ("apache")); config = source.Configs["server"]; Assert.AreEqual ("http://nini.sf.net/", config.Get ("domain")); } [TestMethod] public void ExpandKeyValuesMerge () { StringWriter writer = new StringWriter (); writer.WriteLine ("[web]"); writer.WriteLine (" protocol = http"); writer.WriteLine ("[server]"); writer.WriteLine (" domain1 = ${web|protocol}://nini.sf.net/"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); StringWriter newWriter = new StringWriter (); newWriter.WriteLine ("[web]"); newWriter.WriteLine (" apache = Apache implements ${protocol}"); newWriter.WriteLine ("[server]"); newWriter.WriteLine (" domain2 = ${web|protocol}://nini.sf.net/"); IniConfigSource newSource = new IniConfigSource (new StringReader (newWriter.ToString ())); source.Merge (newSource); source.ExpandKeyValues (); IConfig config = source.Configs["web"]; Assert.AreEqual ("http", config.Get ("protocol")); Assert.AreEqual ("Apache implements http", config.Get ("apache")); config = source.Configs["server"]; Assert.AreEqual ("http://nini.sf.net/", config.Get ("domain1")); Assert.AreEqual ("http://nini.sf.net/", config.Get ("domain2")); } [TestMethod] public void AddNewConfigsAndKeys () { // Add some new configs and keys here and test. StringWriter writer = new StringWriter (); writer.WriteLine ("[Pets]"); writer.WriteLine (" cat = muffy"); writer.WriteLine (" dog = rover"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["Pets"]; Assert.AreEqual ("Pets", config.Name); Assert.AreEqual (2, config.GetKeys ().Length); IConfig newConfig = source.AddConfig ("NewTest"); newConfig.Set ("Author", "Brent"); newConfig.Set ("Birthday", "February 8th"); newConfig = source.AddConfig ("AnotherNew"); Assert.AreEqual (3, source.Configs.Count); config = source.Configs["NewTest"]; Assert.IsNotNull (config); Assert.AreEqual (2, config.GetKeys ().Length); Assert.AreEqual ("February 8th", config.Get ("Birthday")); Assert.AreEqual ("Brent", config.Get ("Author")); } [TestMethod] public void GetBooleanSpace () { StringWriter textWriter = new StringWriter (); XmlTextWriter xmlWriter = NiniWriter (textWriter); WriteSection (xmlWriter, "Pets"); WriteKey (xmlWriter, "cat", "muffy"); WriteKey (xmlWriter, "dog", "rover"); WriteKey (xmlWriter, "Is Mammal", "False"); xmlWriter.WriteEndDocument (); StringReader reader = new StringReader (textWriter.ToString ()); XmlTextReader xmlReader = new XmlTextReader (reader); XmlConfigSource source = new XmlConfigSource (xmlReader); source.Alias.AddAlias ("true", true); source.Alias.AddAlias ("false", false); Assert.IsFalse (source.Configs["Pets"].GetBoolean ("Is Mammal", false)); } [TestMethod] public void RemoveNonExistingKey () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Pets]"); writer.WriteLine (" cat = muffy"); writer.WriteLine (" dog = rover"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); // This should not throw an exception source.Configs["Pets"].Remove ("Not here"); } [TestMethod] public void SavingWithNonStrings () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Pets]"); writer.WriteLine (" cat = muffy"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); StringWriter newWriter = new StringWriter (); IConfig config = source.Configs["Pets"]; Assert.AreEqual ("Pets", config.Name); config.Set ("count", 1); source.Save (newWriter); } [TestMethod] public void ConfigSourceEvents () { string filePath = "EventTest.ini"; IniConfigSource source = new IniConfigSource (); source.Saved += new EventHandler (this.source_saved); source.Reloaded += new EventHandler (this.source_reloaded); Assert.IsNull (eventConfig); Assert.IsNull (eventSource); IConfig config = source.AddConfig ("Test"); eventSource = null; Assert.AreEqual (savedCount, 0); source.Save (filePath); Assert.AreEqual (savedCount, 1); Assert.IsTrue (source == eventSource); eventSource = null; source.Save (); Assert.AreEqual (savedCount, 2); Assert.IsTrue (source == eventSource); eventSource = null; Assert.AreEqual (reloadedCount, 0); source.Reload (); Assert.AreEqual (reloadedCount, 1); Assert.IsTrue (source == eventSource); File.Delete (filePath); } [TestMethod] public void ConfigEvents () { IConfigSource source = new IniConfigSource (); IConfig config = source.AddConfig ("Test"); config.KeySet += new ConfigKeyEventHandler (this.config_keySet); config.KeyRemoved += new ConfigKeyEventHandler (this.config_keyRemoved); // Set key events Assert.AreEqual (keySetCount, 0); config.Set ("Test 1", "Value 1"); Assert.AreEqual (keySetCount, 1); Assert.AreEqual ("Test 1", keyName); Assert.AreEqual ("Value 1", keyValue); config.Set ("Test 2", "Value 2"); Assert.AreEqual (keySetCount, 2); Assert.AreEqual ("Test 2", keyName); Assert.AreEqual ("Value 2", keyValue); // Remove key events Assert.AreEqual (keyRemovedCount, 0); config.Remove ("Test 1"); Assert.AreEqual (keyRemovedCount, 1); Assert.AreEqual ("Test 1", keyName); Assert.AreEqual ("Value 1", keyValue); config.Remove ("Test 2"); Assert.AreEqual (keyRemovedCount, 2); Assert.AreEqual ("Test 2", keyName); Assert.AreEqual ("Value 2", keyValue); } [TestMethod] public void ExpandKeyValuesConfigError () { StringWriter writer = new StringWriter (); writer.WriteLine ("[server]"); writer.WriteLine (" domain1 = ${web|protocol}://nini.sf.net/"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); try { source.ExpandKeyValues (); } catch (Exception ex) { Assert.AreEqual ("Expand config not found: web", ex.Message); } } [TestMethod] public void ExpandKeyValuesKeyError () { StringWriter writer = new StringWriter (); writer.WriteLine ("[web]"); writer.WriteLine ("not-protocol = hah!"); writer.WriteLine ("[server]"); writer.WriteLine (" domain1 = ${web|protocol}://nini.sf.net/"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); try { source.ExpandKeyValues (); } catch (Exception ex) { Assert.AreEqual ("Expand key not found: protocol", ex.Message); } } [TestMethod] public void ExpandKeyInfiniteRecursion () { StringWriter writer = new StringWriter (); writer.WriteLine ("[replace]"); writer.WriteLine ("test = ${test} broken"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); try { source.ExpandKeyValues (); } catch (ArgumentException ex) { Assert.AreEqual ("Key cannot have a expand value of itself: test", ex.Message); } } [TestMethod] public void ConfigBaseGetErrors () { StringWriter writer = new StringWriter (); writer.WriteLine ("[web]"); writer.WriteLine ("; No keys"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.Configs["web"]; try { config.GetInt ("not_there"); } catch (Exception ex) { Assert.AreEqual ("Value not found: not_there", ex.Message); } try { config.GetFloat ("not_there"); } catch (Exception ex) { Assert.AreEqual ("Value not found: not_there", ex.Message); } try { config.GetDouble ("not_there"); } catch (Exception ex) { Assert.AreEqual ("Value not found: not_there", ex.Message); } try { config.GetLong ("not_there"); } catch (Exception ex) { Assert.AreEqual ("Value not found: not_there", ex.Message); } try { config.GetBoolean ("not_there"); } catch (Exception ex) { Assert.AreEqual ("Value not found: not_there", ex.Message); } } [TestInitialize] public void Setup () { eventConfig = null; eventSource = null; savedCount = 0; keySetCount = 0; keyRemovedCount = 0; } #endregion #region Private methods private void source_saved (object sender, EventArgs e) { savedCount++; eventSource = (IConfigSource)sender; } private void source_reloaded (object sender, EventArgs e) { reloadedCount++; eventSource = (IConfigSource)sender; } private void config_keySet (object sender, ConfigKeyEventArgs e) { keySetCount++; keyName = e.KeyName; keyValue = e.KeyValue; eventConfig = (IConfig)sender; } private void config_keyRemoved (object sender, ConfigKeyEventArgs e) { keyRemovedCount++; keyName = e.KeyName; keyValue = e.KeyValue; eventConfig = (IConfig)sender; } private XmlTextWriter NiniWriter (TextWriter writer) { XmlTextWriter result = new XmlTextWriter (writer); result.WriteStartDocument (); result.WriteStartElement ("Nini"); return result; } private void WriteSection (XmlWriter writer, string sectionName) { writer.WriteStartElement ("Section"); writer.WriteAttributeString ("Name", sectionName); } private void WriteKey (XmlWriter writer, string key, string value) { writer.WriteStartElement ("Key"); writer.WriteAttributeString ("Name", key); writer.WriteAttributeString ("Value", value); writer.WriteEndElement (); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.PetstoreV2AllSync { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Extension methods for SwaggerPetstoreV2. /// </summary> public static partial class SwaggerPetstoreV2Extensions { /// <summary> /// Add a new pet to the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static Pet AddPet(this ISwaggerPetstoreV2 operations, Pet body) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).AddPetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Add a new pet to the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Pet> AddPetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Add a new pet to the store /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<Pet> AddPetWithHttpMessages(this ISwaggerPetstoreV2 operations, Pet body, Dictionary<string, List<string>> customHeaders = null) { return operations.AddPetWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static void UpdatePet(this ISwaggerPetstoreV2 operations, Pet body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Update an existing pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse UpdatePetWithHttpMessages(this ISwaggerPetstoreV2 operations, Pet body, Dictionary<string, List<string>> customHeaders = null) { return operations.UpdatePetWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> public static IList<Pet> FindPetsByStatus(this ISwaggerPetstoreV2 operations, IList<string> status) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByStatusAsync(status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByStatusAsync(this ISwaggerPetstoreV2 operations, IList<string> status, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<IList<Pet>> FindPetsByStatusWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<string> status, Dictionary<string, List<string>> customHeaders = null) { return operations.FindPetsByStatusWithHttpMessagesAsync(status, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> public static IList<Pet> FindPetsByTags(this ISwaggerPetstoreV2 operations, IList<string> tags) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByTagsAsync(tags), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByTagsAsync(this ISwaggerPetstoreV2 operations, IList<string> tags, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<IList<Pet>> FindPetsByTagsWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<string> tags, Dictionary<string, List<string>> customHeaders = null) { return operations.FindPetsByTagsWithHttpMessagesAsync(tags, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Find pet by Id /// </summary> /// <remarks> /// Returns a single pet /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet to return /// </param> public static Pet GetPetById(this ISwaggerPetstoreV2 operations, long petId) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetPetByIdAsync(petId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Find pet by Id /// </summary> /// <remarks> /// Returns a single pet /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet to return /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Pet> GetPetByIdAsync(this ISwaggerPetstoreV2 operations, long petId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Find pet by Id /// </summary> /// <remarks> /// Returns a single pet /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet to return /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<Pet> GetPetByIdWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, Dictionary<string, List<string>> customHeaders = null) { return operations.GetPetByIdWithHttpMessagesAsync(petId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> public static void UpdatePetWithForm(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string)) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetWithFormAsync(petId, fileContent, fileName, status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePetWithFormAsync(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse UpdatePetWithFormWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), Dictionary<string, List<string>> customHeaders = null) { return operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> public static void DeletePet(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "") { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeletePetAsync(petId, apiKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeletePetAsync(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse DeletePetWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", Dictionary<string, List<string>> customHeaders = null) { return operations.DeletePetWithHttpMessagesAsync(petId, apiKey, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IDictionary<string, int?> GetInventory(this ISwaggerPetstoreV2 operations) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetInventoryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IDictionary<string, int?>> GetInventoryAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<IDictionary<string, int?>> GetInventoryWithHttpMessages(this ISwaggerPetstoreV2 operations, Dictionary<string, List<string>> customHeaders = null) { return operations.GetInventoryWithHttpMessagesAsync(customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> public static Order PlaceOrder(this ISwaggerPetstoreV2 operations, Order body) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).PlaceOrderAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Order> PlaceOrderAsync(this ISwaggerPetstoreV2 operations, Order body, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Place an order for a pet /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<Order> PlaceOrderWithHttpMessages(this ISwaggerPetstoreV2 operations, Order body, Dictionary<string, List<string>> customHeaders = null) { return operations.PlaceOrderWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Find purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> public static Order GetOrderById(this ISwaggerPetstoreV2 operations, string orderId) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetOrderByIdAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Find purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Order> GetOrderByIdAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Find purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<Order> GetOrderByIdWithHttpMessages(this ISwaggerPetstoreV2 operations, string orderId, Dictionary<string, List<string>> customHeaders = null) { return operations.GetOrderByIdWithHttpMessagesAsync(orderId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Delete purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> public static void DeleteOrder(this ISwaggerPetstoreV2 operations, string orderId) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteOrderAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteOrderAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse DeleteOrderWithHttpMessages(this ISwaggerPetstoreV2 operations, string orderId, Dictionary<string, List<string>> customHeaders = null) { return operations.DeleteOrderWithHttpMessagesAsync(orderId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> public static void CreateUser(this ISwaggerPetstoreV2 operations, User body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUserAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUserAsync(this ISwaggerPetstoreV2 operations, User body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// Created user object /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse CreateUserWithHttpMessages(this ISwaggerPetstoreV2 operations, User body, Dictionary<string, List<string>> customHeaders = null) { return operations.CreateUserWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithArrayInput(this ISwaggerPetstoreV2 operations, IList<User> body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithArrayInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUsersWithArrayInputAsync(this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse CreateUsersWithArrayInputWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<User> body, Dictionary<string, List<string>> customHeaders = null) { return operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithListInput(this ISwaggerPetstoreV2 operations, IList<User> body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithListInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateUsersWithListInputAsync(this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse CreateUsersWithListInputWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<User> body, Dictionary<string, List<string>> customHeaders = null) { return operations.CreateUsersWithListInputWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> public static string LoginUser(this ISwaggerPetstoreV2 operations, string username, string password) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LoginUserAsync(username, password), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> LoginUserAsync(this ISwaggerPetstoreV2 operations, string username, string password, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Logs user into the system /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<string,LoginUserHeaders> LoginUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, string password, Dictionary<string, List<string>> customHeaders = null) { return operations.LoginUserWithHttpMessagesAsync(username, password, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void LogoutUser(this ISwaggerPetstoreV2 operations) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LogoutUserAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task LogoutUserAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse LogoutUserWithHttpMessages(this ISwaggerPetstoreV2 operations, Dictionary<string, List<string>> customHeaders = null) { return operations.LogoutUserWithHttpMessagesAsync(customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> public static User GetUserByName(this ISwaggerPetstoreV2 operations, string username) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetUserByNameAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<User> GetUserByNameAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get user by user name /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse<User> GetUserByNameWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, Dictionary<string, List<string>> customHeaders = null) { return operations.GetUserByNameWithHttpMessagesAsync(username, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> public static void UpdateUser(this ISwaggerPetstoreV2 operations, string username, User body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdateUserAsync(username, body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateUserAsync(this ISwaggerPetstoreV2 operations, string username, User body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse UpdateUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, User body, Dictionary<string, List<string>> customHeaders = null) { return operations.UpdateUserWithHttpMessagesAsync(username, body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> public static void DeleteUser(this ISwaggerPetstoreV2 operations, string username) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteUserAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteUserAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse DeleteUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, Dictionary<string, List<string>> customHeaders = null) { return operations.DeleteUserWithHttpMessagesAsync(username, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); } } }
/* * 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 Directory = Lucene.Net.Store.Directory; using IndexInput = Lucene.Net.Store.IndexInput; using IndexOutput = Lucene.Net.Store.IndexOutput; namespace Lucene.Net.Util { /// <summary>Optimized implementation of a vector of bits. This is more-or-less like /// java.util.BitSet, but also includes the following: /// <ul> /// <li>a count() method, which efficiently computes the number of one bits;</li> /// <li>optimized read from and write to disk;</li> /// <li>inlinable get() method;</li> /// <li>store and load, as bit set or d-gaps, depending on sparseness;</li> /// </ul> /// </summary> /// <version> $Id: BitVector.java 564236 2007-08-09 15:21:19Z gsingers $ /// </version> public sealed class BitVector { private byte[] bits; private int size; private int count = - 1; /// <summary>Constructs a vector capable of holding <code>n</code> bits. </summary> public BitVector(int n) { size = n; bits = new byte[(size >> 3) + 1]; } /// <summary>Sets the value of <code>bit</code> to one. </summary> public void Set(int bit) { if (bit >= size) { throw new System.IndexOutOfRangeException("Index of bound " + bit); } bits[bit >> 3] |= (byte) (1 << (bit & 7)); count = - 1; } /// <summary>Sets the value of <code>bit</code> to zero. </summary> public void Clear(int bit) { if (bit >= size) { throw new System.IndexOutOfRangeException("Index of bound " + bit); } bits[bit >> 3] &= (byte) (~ (1 << (bit & 7))); count = - 1; } /// <summary> /// Sets the value of bit to true and returns true if bit was already set. /// </summary> /// <param name="bit"></param> /// <returns>true if bit was already set</returns> public bool GetAndSet(int bit) { if (bit >= size) throw new IndexOutOfRangeException("bit (" + bit + ") is out of this bit vector's range (" + size + ")"); int pos = bit >> 3; int v = bits[pos]; int flag = 1 << (bit & 7); if ((flag & v) != 0) { return true; } else { bits[pos] = (byte)(v | flag); if (count != -1) count++; return false; } } /// <summary>Returns <code>true</code> if <code>bit</code> is one and /// <code>false</code> if it is zero. /// </summary> public bool Get(int bit) { if (bit >= size) { throw new System.IndexOutOfRangeException("Index of bound " + bit); } return (bits[bit >> 3] & (1 << (bit & 7))) != 0; } /// <summary>Returns the number of bits in this vector. This is also one greater than /// the number of the largest valid bit number. /// </summary> public int Size() { return size; } /// <summary>Returns the total number of one bits in this vector. This is efficiently /// computed and cached, so that, if the vector is not changed, no /// recomputation is done for repeated calls. /// </summary> public int Count() { // if the vector has been modified if (count == - 1) { int c = 0; int end = bits.Length; for (int i = 0; i < end; i++) c += BYTE_COUNTS[bits[i] & 0xFF]; // sum bits per byte count = c; } return count; } private static readonly byte[] BYTE_COUNTS = new byte[]{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8}; /// <summary>Writes this vector to the file <code>name</code> in Directory /// <code>d</code>, in a format that can be read by the constructor {@link /// #BitVector(Directory, String)}. /// </summary> public void Write(Directory d, System.String name) { IndexOutput output = d.CreateOutput(name); try { if (IsSparse()) { WriteDgaps(output); // sparse bit-set more efficiently saved as d-gaps. } else { WriteBits(output); } } finally { output.Close(); } } /// <summary>Write as a bit set </summary> private void WriteBits(IndexOutput output) { output.WriteInt(Size()); // write size output.WriteInt(Count()); // write count output.WriteBytes(bits, bits.Length); } /// <summary>Write as a d-gaps list </summary> private void WriteDgaps(IndexOutput output) { output.WriteInt(- 1); // mark using d-gaps output.WriteInt(Size()); // write size output.WriteInt(Count()); // write count int last = 0; int n = Count(); int m = bits.Length; for (int i = 0; i < m && n > 0; i++) { if (bits[i] != 0) { output.WriteVInt(i - last); output.WriteByte(bits[i]); last = i; n -= BYTE_COUNTS[bits[i] & 0xFF]; } } } /// <summary>Indicates if the bit vector is sparse and should be saved as a d-gaps list, or dense, and should be saved as a bit set. </summary> private bool IsSparse() { // note: order of comparisons below set to favor smaller values (no binary range search.) // note: adding 4 because we start with ((int) -1) to indicate d-gaps format. // note: we write the d-gap for the byte number, and the byte (bits[i]) itself, therefore // multiplying count by (8+8) or (8+16) or (8+24) etc.: // - first 8 for writing bits[i] (1 byte vs. 1 bit), and // - second part for writing the byte-number d-gap as vint. // note: factor is for read/write of byte-arrays being faster than vints. int factor = 10; if (bits.Length < (1 << 7)) return factor * (4 + (8 + 8) * Count()) < Size(); if (bits.Length < (1 << 14)) return factor * (4 + (8 + 16) * Count()) < Size(); if (bits.Length < (1 << 21)) return factor * (4 + (8 + 24) * Count()) < Size(); if (bits.Length < (1 << 28)) return factor * (4 + (8 + 32) * Count()) < Size(); return factor * (4 + (8 + 40) * Count()) < Size(); } /// <summary>Constructs a bit vector from the file <code>name</code> in Directory /// <code>d</code>, as written by the {@link #write} method. /// </summary> public BitVector(Directory d, System.String name) { IndexInput input = d.OpenInput(name); try { size = input.ReadInt(); // read size if (size == - 1) { ReadDgaps(input); } else { ReadBits(input); } } finally { input.Close(); } } /// <summary>Read as a bit set </summary> private void ReadBits(IndexInput input) { count = input.ReadInt(); // read count bits = new byte[(size >> 3) + 1]; // allocate bits input.ReadBytes(bits, 0, bits.Length); } /// <summary>read as a d-gaps list </summary> private void ReadDgaps(IndexInput input) { size = input.ReadInt(); // (re)read size count = input.ReadInt(); // read count bits = new byte[(size >> 3) + 1]; // allocate bits int last = 0; int n = Count(); while (n > 0) { last += input.ReadVInt(); bits[last] = input.ReadByte(); n -= BYTE_COUNTS[bits[last] & 0xFF]; } } } }
// UMA Auto genered code, DO NOT MODIFY!!! // All changes to this file will be destroyed without warning or confirmation! // Use double { to escape a single curly bracket // // template junk executed per dna Field , the accumulated content is available through the {0:ID} tag // //#TEMPLATE GetValues UmaDnaChild_GetIndex_Fragment.cs.txt //#TEMPLATE SetValues UmaDnaChild_SetIndex_Fragment.cs.txt //#TEMPLATE GetValue UmaDnaChild_GetValue_Fragment.cs.txt //#TEMPLATE SetValue UmaDnaChild_SetValue_Fragment.cs.txt //#TEMPLATE GetNames UmaDnaChild_GetNames_Fragment.cs.txt // // Byte Serialization Handling // //#TEMPLATE Byte_Fields UmaDnaChild_Byte_Fields_Fragment.cs.txt //#TEMPLATE Byte_ToDna UmaDnaChild_Byte_ToDna_Fragment.cs.txt //#TEMPLATE Byte_FromDna UmaDnaChild_Byte_FromDna_Fragment.cs.txt // namespace UMA { public partial class UMADnaHumanoid { public override int Count { get { return 46; } } public override float[] Values { get { return new float[] { height, headSize, headWidth, neckThickness, armLength, forearmLength, armWidth, forearmWidth, handsSize, feetSize, legSeparation, upperMuscle, lowerMuscle, upperWeight, lowerWeight, legsSize, belly, waist, gluteusSize, earsSize, earsPosition, earsRotation, noseSize, noseCurve, noseWidth, noseInclination, nosePosition, nosePronounced, noseFlatten, chinSize, chinPronounced, chinPosition, mandibleSize, jawsSize, jawsPosition, cheekSize, cheekPosition, lowCheekPronounced, lowCheekPosition, foreheadSize, foreheadPosition, lipsSize, mouthSize, eyeRotation, eyeSize, breastSize, }; } set { height = value[0]; headSize = value[1]; headWidth = value[2]; neckThickness = value[3]; armLength = value[4]; forearmLength = value[5]; armWidth = value[6]; forearmWidth = value[7]; handsSize = value[8]; feetSize = value[9]; legSeparation = value[10]; upperMuscle = value[11]; lowerMuscle = value[12]; upperWeight = value[13]; lowerWeight = value[14]; legsSize = value[15]; belly = value[16]; waist = value[17]; gluteusSize = value[18]; earsSize = value[19]; earsPosition = value[20]; earsRotation = value[21]; noseSize = value[22]; noseCurve = value[23]; noseWidth = value[24]; noseInclination = value[25]; nosePosition = value[26]; nosePronounced = value[27]; noseFlatten = value[28]; chinSize = value[29]; chinPronounced = value[30]; chinPosition = value[31]; mandibleSize = value[32]; jawsSize = value[33]; jawsPosition = value[34]; cheekSize = value[35]; cheekPosition = value[36]; lowCheekPronounced = value[37]; lowCheekPosition = value[38]; foreheadSize = value[39]; foreheadPosition = value[40]; lipsSize = value[41]; mouthSize = value[42]; eyeRotation = value[43]; eyeSize = value[44]; breastSize = value[45]; } } public override float GetValue(int idx) { switch(idx) { case 0: return height; case 1: return headSize; case 2: return headWidth; case 3: return neckThickness; case 4: return armLength; case 5: return forearmLength; case 6: return armWidth; case 7: return forearmWidth; case 8: return handsSize; case 9: return feetSize; case 10: return legSeparation; case 11: return upperMuscle; case 12: return lowerMuscle; case 13: return upperWeight; case 14: return lowerWeight; case 15: return legsSize; case 16: return belly; case 17: return waist; case 18: return gluteusSize; case 19: return earsSize; case 20: return earsPosition; case 21: return earsRotation; case 22: return noseSize; case 23: return noseCurve; case 24: return noseWidth; case 25: return noseInclination; case 26: return nosePosition; case 27: return nosePronounced; case 28: return noseFlatten; case 29: return chinSize; case 30: return chinPronounced; case 31: return chinPosition; case 32: return mandibleSize; case 33: return jawsSize; case 34: return jawsPosition; case 35: return cheekSize; case 36: return cheekPosition; case 37: return lowCheekPronounced; case 38: return lowCheekPosition; case 39: return foreheadSize; case 40: return foreheadPosition; case 41: return lipsSize; case 42: return mouthSize; case 43: return eyeRotation; case 44: return eyeSize; case 45: return breastSize; } throw new System.ArgumentOutOfRangeException(); } public override void SetValue(int idx, float value) { switch(idx) { case 0: height = value; return; case 1: headSize = value; return; case 2: headWidth = value; return; case 3: neckThickness = value; return; case 4: armLength = value; return; case 5: forearmLength = value; return; case 6: armWidth = value; return; case 7: forearmWidth = value; return; case 8: handsSize = value; return; case 9: feetSize = value; return; case 10: legSeparation = value; return; case 11: upperMuscle = value; return; case 12: lowerMuscle = value; return; case 13: upperWeight = value; return; case 14: lowerWeight = value; return; case 15: legsSize = value; return; case 16: belly = value; return; case 17: waist = value; return; case 18: gluteusSize = value; return; case 19: earsSize = value; return; case 20: earsPosition = value; return; case 21: earsRotation = value; return; case 22: noseSize = value; return; case 23: noseCurve = value; return; case 24: noseWidth = value; return; case 25: noseInclination = value; return; case 26: nosePosition = value; return; case 27: nosePronounced = value; return; case 28: noseFlatten = value; return; case 29: chinSize = value; return; case 30: chinPronounced = value; return; case 31: chinPosition = value; return; case 32: mandibleSize = value; return; case 33: jawsSize = value; return; case 34: jawsPosition = value; return; case 35: cheekSize = value; return; case 36: cheekPosition = value; return; case 37: lowCheekPronounced = value; return; case 38: lowCheekPosition = value; return; case 39: foreheadSize = value; return; case 40: foreheadPosition = value; return; case 41: lipsSize = value; return; case 42: mouthSize = value; return; case 43: eyeRotation = value; return; case 44: eyeSize = value; return; case 45: breastSize = value; return; } throw new System.ArgumentOutOfRangeException(); } public static string[] GetNames() { return new string[] { "height", "headSize", "headWidth", "neckThickness", "armLength", "forearmLength", "armWidth", "forearmWidth", "handsSize", "feetSize", "legSeparation", "upperMuscle", "lowerMuscle", "upperWeight", "lowerWeight", "legsSize", "belly", "waist", "gluteusSize", "earsSize", "earsPosition", "earsRotation", "noseSize", "noseCurve", "noseWidth", "noseInclination", "nosePosition", "nosePronounced", "noseFlatten", "chinSize", "chinPronounced", "chinPosition", "mandibleSize", "jawsSize", "jawsPosition", "cheekSize", "cheekPosition", "lowCheekPronounced", "lowCheekPosition", "foreheadSize", "foreheadPosition", "lipsSize", "mouthSize", "eyeRotation", "eyeSize", "breastSize", }; } public override string[] Names { get { return GetNames(); } } public static UMADnaHumanoid LoadInstance(string data) { return UnityEngine.JsonUtility.FromJson<UMADnaHumanoid_Byte>(data).ToDna(); } public static string SaveInstance(UMADnaHumanoid instance) { return UnityEngine.JsonUtility.ToJson(UMADnaHumanoid_Byte.FromDna(instance)); } } [System.Serializable] public class UMADnaHumanoid_Byte { public System.Byte height; public System.Byte headSize; public System.Byte headWidth; public System.Byte neckThickness; public System.Byte armLength; public System.Byte forearmLength; public System.Byte armWidth; public System.Byte forearmWidth; public System.Byte handsSize; public System.Byte feetSize; public System.Byte legSeparation; public System.Byte upperMuscle; public System.Byte lowerMuscle; public System.Byte upperWeight; public System.Byte lowerWeight; public System.Byte legsSize; public System.Byte belly; public System.Byte waist; public System.Byte gluteusSize; public System.Byte earsSize; public System.Byte earsPosition; public System.Byte earsRotation; public System.Byte noseSize; public System.Byte noseCurve; public System.Byte noseWidth; public System.Byte noseInclination; public System.Byte nosePosition; public System.Byte nosePronounced; public System.Byte noseFlatten; public System.Byte chinSize; public System.Byte chinPronounced; public System.Byte chinPosition; public System.Byte mandibleSize; public System.Byte jawsSize; public System.Byte jawsPosition; public System.Byte cheekSize; public System.Byte cheekPosition; public System.Byte lowCheekPronounced; public System.Byte lowCheekPosition; public System.Byte foreheadSize; public System.Byte foreheadPosition; public System.Byte lipsSize; public System.Byte mouthSize; public System.Byte eyeRotation; public System.Byte eyeSize; public System.Byte breastSize; public UMADnaHumanoid ToDna() { var res = new UMADnaHumanoid(); res.height = height * (1f / 255f); res.headSize = headSize * (1f / 255f); res.headWidth = headWidth * (1f / 255f); res.neckThickness = neckThickness * (1f / 255f); res.armLength = armLength * (1f / 255f); res.forearmLength = forearmLength * (1f / 255f); res.armWidth = armWidth * (1f / 255f); res.forearmWidth = forearmWidth * (1f / 255f); res.handsSize = handsSize * (1f / 255f); res.feetSize = feetSize * (1f / 255f); res.legSeparation = legSeparation * (1f / 255f); res.upperMuscle = upperMuscle * (1f / 255f); res.lowerMuscle = lowerMuscle * (1f / 255f); res.upperWeight = upperWeight * (1f / 255f); res.lowerWeight = lowerWeight * (1f / 255f); res.legsSize = legsSize * (1f / 255f); res.belly = belly * (1f / 255f); res.waist = waist * (1f / 255f); res.gluteusSize = gluteusSize * (1f / 255f); res.earsSize = earsSize * (1f / 255f); res.earsPosition = earsPosition * (1f / 255f); res.earsRotation = earsRotation * (1f / 255f); res.noseSize = noseSize * (1f / 255f); res.noseCurve = noseCurve * (1f / 255f); res.noseWidth = noseWidth * (1f / 255f); res.noseInclination = noseInclination * (1f / 255f); res.nosePosition = nosePosition * (1f / 255f); res.nosePronounced = nosePronounced * (1f / 255f); res.noseFlatten = noseFlatten * (1f / 255f); res.chinSize = chinSize * (1f / 255f); res.chinPronounced = chinPronounced * (1f / 255f); res.chinPosition = chinPosition * (1f / 255f); res.mandibleSize = mandibleSize * (1f / 255f); res.jawsSize = jawsSize * (1f / 255f); res.jawsPosition = jawsPosition * (1f / 255f); res.cheekSize = cheekSize * (1f / 255f); res.cheekPosition = cheekPosition * (1f / 255f); res.lowCheekPronounced = lowCheekPronounced * (1f / 255f); res.lowCheekPosition = lowCheekPosition * (1f / 255f); res.foreheadSize = foreheadSize * (1f / 255f); res.foreheadPosition = foreheadPosition * (1f / 255f); res.lipsSize = lipsSize * (1f / 255f); res.mouthSize = mouthSize * (1f / 255f); res.eyeRotation = eyeRotation * (1f / 255f); res.eyeSize = eyeSize * (1f / 255f); res.breastSize = breastSize * (1f / 255f); return res; } public static UMADnaHumanoid_Byte FromDna(UMADnaHumanoid dna) { var res = new UMADnaHumanoid_Byte(); res.height = (System.Byte)(dna.height * 255f+0.5f); res.headSize = (System.Byte)(dna.headSize * 255f+0.5f); res.headWidth = (System.Byte)(dna.headWidth * 255f+0.5f); res.neckThickness = (System.Byte)(dna.neckThickness * 255f+0.5f); res.armLength = (System.Byte)(dna.armLength * 255f+0.5f); res.forearmLength = (System.Byte)(dna.forearmLength * 255f+0.5f); res.armWidth = (System.Byte)(dna.armWidth * 255f+0.5f); res.forearmWidth = (System.Byte)(dna.forearmWidth * 255f+0.5f); res.handsSize = (System.Byte)(dna.handsSize * 255f+0.5f); res.feetSize = (System.Byte)(dna.feetSize * 255f+0.5f); res.legSeparation = (System.Byte)(dna.legSeparation * 255f+0.5f); res.upperMuscle = (System.Byte)(dna.upperMuscle * 255f+0.5f); res.lowerMuscle = (System.Byte)(dna.lowerMuscle * 255f+0.5f); res.upperWeight = (System.Byte)(dna.upperWeight * 255f+0.5f); res.lowerWeight = (System.Byte)(dna.lowerWeight * 255f+0.5f); res.legsSize = (System.Byte)(dna.legsSize * 255f+0.5f); res.belly = (System.Byte)(dna.belly * 255f+0.5f); res.waist = (System.Byte)(dna.waist * 255f+0.5f); res.gluteusSize = (System.Byte)(dna.gluteusSize * 255f+0.5f); res.earsSize = (System.Byte)(dna.earsSize * 255f+0.5f); res.earsPosition = (System.Byte)(dna.earsPosition * 255f+0.5f); res.earsRotation = (System.Byte)(dna.earsRotation * 255f+0.5f); res.noseSize = (System.Byte)(dna.noseSize * 255f+0.5f); res.noseCurve = (System.Byte)(dna.noseCurve * 255f+0.5f); res.noseWidth = (System.Byte)(dna.noseWidth * 255f+0.5f); res.noseInclination = (System.Byte)(dna.noseInclination * 255f+0.5f); res.nosePosition = (System.Byte)(dna.nosePosition * 255f+0.5f); res.nosePronounced = (System.Byte)(dna.nosePronounced * 255f+0.5f); res.noseFlatten = (System.Byte)(dna.noseFlatten * 255f+0.5f); res.chinSize = (System.Byte)(dna.chinSize * 255f+0.5f); res.chinPronounced = (System.Byte)(dna.chinPronounced * 255f+0.5f); res.chinPosition = (System.Byte)(dna.chinPosition * 255f+0.5f); res.mandibleSize = (System.Byte)(dna.mandibleSize * 255f+0.5f); res.jawsSize = (System.Byte)(dna.jawsSize * 255f+0.5f); res.jawsPosition = (System.Byte)(dna.jawsPosition * 255f+0.5f); res.cheekSize = (System.Byte)(dna.cheekSize * 255f+0.5f); res.cheekPosition = (System.Byte)(dna.cheekPosition * 255f+0.5f); res.lowCheekPronounced = (System.Byte)(dna.lowCheekPronounced * 255f+0.5f); res.lowCheekPosition = (System.Byte)(dna.lowCheekPosition * 255f+0.5f); res.foreheadSize = (System.Byte)(dna.foreheadSize * 255f+0.5f); res.foreheadPosition = (System.Byte)(dna.foreheadPosition * 255f+0.5f); res.lipsSize = (System.Byte)(dna.lipsSize * 255f+0.5f); res.mouthSize = (System.Byte)(dna.mouthSize * 255f+0.5f); res.eyeRotation = (System.Byte)(dna.eyeRotation * 255f+0.5f); res.eyeSize = (System.Byte)(dna.eyeSize * 255f+0.5f); res.breastSize = (System.Byte)(dna.breastSize * 255f+0.5f); return res; } } }
// -------------------------------------------------------------------------------------------- #region // Copyright (c) 2014, SIL International. // <copyright from='2003' to='2014' company='SIL International'> // Copyright (c) 2014, SIL International. // // Distributable under the terms of the MIT License (http://sil.mit-license.org/) // </copyright> #endregion // // File: ScrPassageControlTest.cs // -------------------------------------------------------------------------------------------- using System; using System.Diagnostics.CodeAnalysis; using System.Windows.Forms; using NUnit.Framework; using SIL.ScriptureUtils; namespace SIL.ScriptureControls { #region Dummy test classes for accessing protected properties/methods /// ---------------------------------------------------------------------------------------- /// <summary> /// Dummy test class for testing <see cref="ScrPassageControl"/> /// </summary> /// ---------------------------------------------------------------------------------------- internal class DummyScrPassageControl: ScrPassageControl { /// ------------------------------------------------------------------------------------ /// <summary> /// Create a new <see cref="ScrPassageDropDown"/> object /// </summary> /// <param name="owner">The owner</param> /// <returns>A new object</returns> /// <remarks>Added this method to allow test class create it's own derived control /// </remarks> /// ------------------------------------------------------------------------------------ protected override ScrPassageDropDown CreateScrPassageDropDown(ScrPassageControl owner) { return new DummyScrPassageDropDown(owner, m_versification); } /// ------------------------------------------------------------------------------------ /// <summary> /// Simulates sending a keypress to the text box portion of the control. /// </summary> /// <param name="e"></param> /// ------------------------------------------------------------------------------------ public void PerformKeyDown(KeyEventArgs e) { if (e.KeyCode == Keys.Return) txtScrRef_KeyPress(null, new KeyPressEventArgs('\r')); else txtScrRef_KeyDown(null, e); } #region Properties /// ------------------------------------------------------------------------------------ /// <summary> /// Gets the textbox for the scripture reference /// </summary> /// ------------------------------------------------------------------------------------ internal TextBox ReferenceTextBox { get { return txtScrRef; } } /// ------------------------------------------------------------------------------------ /// <summary> /// Simulate a mouse down on the DropDown button /// </summary> /// ------------------------------------------------------------------------------------ internal void SimulateDropDownButtonClick() { btnScrPsgDropDown_MouseDown(null, new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0)); } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets the drop-down button portion of the control. /// </summary> /// ------------------------------------------------------------------------------------ internal Control DropDownButton { get {return btnScrPsgDropDown;} } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets the <see cref="ScrPassageDropDown"/> /// </summary> /// ------------------------------------------------------------------------------------ internal DummyScrPassageDropDown DropDownWindow { get {return (DummyScrPassageDropDown)m_dropdownForm;} } #endregion #region DummyScrPassageDropDown /// ------------------------------------------------------------------------------------ /// <summary> /// Dummy test class for testing <see cref="ScrPassageDropDown"/> /// </summary> /// ------------------------------------------------------------------------------------ internal class DummyScrPassageDropDown : ScrPassageDropDown { /// -------------------------------------------------------------------------------- /// <summary> /// Initializes a new object /// </summary> /// <param name="owner">The owner.</param> /// <param name="versification">The current versification to use when creating /// instances of BCVRef</param> /// -------------------------------------------------------------------------------- public DummyScrPassageDropDown(ScrPassageControl owner, IScrVers versification) : base(owner, false, versification) { } /// -------------------------------------------------------------------------------- /// <summary> /// /// </summary> /// <param name="e"></param> /// -------------------------------------------------------------------------------- internal void PerformKeyDown(KeyEventArgs e) { OnKeyDown(e); } /// -------------------------------------------------------------------------------- /// <summary> /// /// </summary> /// <param name="e"></param> /// -------------------------------------------------------------------------------- protected override void OnDeactivate(EventArgs e) { } /// -------------------------------------------------------------------------------- /// <summary> /// Sets the current button whose BCVValue property is the same as that specified. /// </summary> /// <param name="bcv">The Book, Chapter, or Verse of the button to make current. /// </param> /// --------------------------------------------------------------------------------- internal void SetCurrentButton(short bcv) { foreach (ScrDropDownButton button in m_buttons) { if (button.BCVValue == bcv) { m_currButton = button.Index; break; } } } /// -------------------------------------------------------------------------------- /// <summary> /// Gets the number of LabelButtons in the drop-down's control collection. /// </summary> /// --------------------------------------------------------------------------------- internal int ButtonsShowing { get { int count = 0; foreach (Control ctrl in this.Controls) { if (ctrl is LabelButton) count++; } return count; } } /// -------------------------------------------------------------------------------- /// <summary> /// Gets a value indicating whether the window will be activated when it is shown. /// </summary> /// <value></value> /// <returns>Always <c>true</c>.</returns> /// -------------------------------------------------------------------------------- protected override bool ShowWithoutActivation { get { return true; } } } #endregion } #endregion /// <summary> /// Tests the Scripture Passage Control /// </summary> [TestFixture] [SuppressMessage("Gendarme.Rules.Design", "TypesWithDisposableFieldsShouldBeDisposableRule", Justification="Unit test - m_ctrlOwner gets disposed in TestTearDown(), m_scp and " + "m_filteredScp get added to m_ctrlOwner.Controls collection")] public class ScrPassageControlTest { private Form m_ctrlOwner; private DummyScrPassageControl m_scp; private DummyScrPassageControl m_filteredScp; private IScrVers m_versification; #region Setup methods /// ------------------------------------------------------------------------------------ [SetUp] public void TestSetup() { m_versification = new TestScrVers(); m_ctrlOwner = new Form(); m_scp = new DummyScrPassageControl(); m_scp.Initialize(new BCVRef(01001001), m_versification); m_filteredScp = new DummyScrPassageControl(); m_filteredScp.Initialize(new BCVRef(01001001), m_versification, new[] { 57, 59, 65 }); m_ctrlOwner.Controls.Add(m_scp); m_ctrlOwner.Controls.Add(m_filteredScp); m_ctrlOwner.CreateControl(); if (m_scp.DropDownWindow != null) m_scp.DropDownWindow.Close(); if (m_filteredScp.DropDownWindow != null) m_filteredScp.DropDownWindow.Close(); } /// ------------------------------------------------------------------------------------ /// <summary> /// End of a test /// </summary> /// ------------------------------------------------------------------------------------ [TearDown] public void TestTearDown() { #if !__MonoCS__ // m_dbScp.SimulateDropDownButtonClick(); can cause this form to hang on close on mono. m_ctrlOwner.Close(); #endif m_ctrlOwner.Dispose(); } #endregion #region Test methods /// ------------------------------------------------------------------------------------ /// <summary> /// Test parsing textual references and getting the text after setting references /// programmatically /// </summary> /// ------------------------------------------------------------------------------------ [Test] public void ValidateReferenceText() { m_scp.Reference = "Gen 1:10"; Assert.IsTrue(m_scp.Valid); m_scp.Reference = "Gen 1:31"; Assert.IsTrue(m_scp.Valid); m_scp.Reference = "Gen 1:0"; Assert.IsTrue(m_scp.Valid); // set to James 3:5 m_scp.ScReference = new BCVRef(59, 3, 5); Assert.AreEqual("JAS 3:5", m_scp.ReferenceTextBox.Text); // Set to Exodus 8:20 m_scp.ScReference = new BCVRef(2, 8, 20); Assert.AreEqual("EXO 8:20", m_scp.ReferenceTextBox.Text); } /// ------------------------------------------------------------------------------------ /// <summary> /// Test that the drop-down window opens and closes properly /// </summary> /// ------------------------------------------------------------------------------------ [Test] public void ScrPassageDropDownBehaviorTests() { if (m_scp.DropDownWindow != null) m_scp.DropDownWindow.Close(); Assert.IsNull(m_scp.DropDownWindow); m_scp.SimulateDropDownButtonClick(); Assert.IsTrue(m_scp.DropDownWindow.Visible); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Escape)); Assert.IsNull(m_scp.DropDownWindow); // Verify that Alt-Down shows the list. m_scp.PerformKeyDown(new KeyEventArgs(Keys.Down | Keys.Alt)); Assert.IsNotNull(m_scp.DropDownWindow); Assert.IsTrue(m_scp.DropDownWindow.Visible); } /// ------------------------------------------------------------------------------------ /// <summary> /// Test parsing textual reference typed into control /// </summary> /// ------------------------------------------------------------------------------------ [Test] public void SettingReferenceByTypingTextTest() { m_scp.ReferenceTextBox.Text = "GEN 2:5"; m_scp.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.AreEqual(1, m_scp.ScReference.Book); Assert.AreEqual(2, m_scp.ScReference.Chapter); Assert.AreEqual(5, m_scp.ScReference.Verse); } /// ------------------------------------------------------------------------------------ /// <summary> /// Test that the reference gets resolved properly when pressing enter when the /// text box has focus. /// </summary> /// ------------------------------------------------------------------------------------ [Test] public void ResolveReferenceOnEnter() { m_scp.ReferenceTextBox.Focus(); m_scp.ReferenceTextBox.Text = "gen"; m_scp.PerformKeyDown(new KeyEventArgs(Keys.Return)); Assert.AreEqual("GEN 1:1", m_scp.ReferenceTextBox.Text); } /// ------------------------------------------------------------------------------------ /// <summary> /// Resolves an incomplete reference when the user types "j" (Joshua is the first book /// that starts with "j") /// </summary> /// ------------------------------------------------------------------------------------ [Test] public void ResolveReference_IncompleteMultilingScrBooks() { m_scp.ReferenceTextBox.Focus(); m_scp.ReferenceTextBox.Text = "j"; m_scp.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.AreEqual("JOS 1:1", m_scp.ReferenceTextBox.Text); } /// ------------------------------------------------------------------------------------ /// <summary> /// Resolves an incomplete reference for James when the user types "j" with /// DBMultilingScrBooks. It is not Joshua, Judges, Job, Jeremiah, Joel, etc because these /// books are not in the list. /// </summary> /// ------------------------------------------------------------------------------------ [Test] public void ResolveReference_IncompleteInFilteredList() { m_filteredScp.ReferenceTextBox.Focus(); m_filteredScp.ReferenceTextBox.Text = "j"; m_filteredScp.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.AreEqual("JAS 1:1", m_filteredScp.ReferenceTextBox.Text); } /// ------------------------------------------------------------------------------------ /// <summary> /// Test resolving an incomplete reference when the user types "q". Since no book begins /// with "q", it should return the first book in our project, which is Philemon. /// </summary> /// ------------------------------------------------------------------------------------ [Test] public void ResolveReference_InvalidBook() { m_filteredScp.ReferenceTextBox.Focus(); m_filteredScp.ReferenceTextBox.Text = "q"; m_filteredScp.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.AreEqual("PHM 1:1", m_filteredScp.ReferenceTextBox.Text); } /// ------------------------------------------------------------------------------------ /// <summary> /// Attempts to resolve an incomplete reference when the user types "p" in the filtered /// control. Even though there are books in the Bible that begin with "p", since no /// books in the filtered list do, the first book in the list should be returned. /// </summary> /// ------------------------------------------------------------------------------------ [Test] public void ResolveReference_IncompleteNotInProject() { m_filteredScp.ReferenceTextBox.Focus(); m_filteredScp.ReferenceTextBox.Text = "p"; m_filteredScp.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.AreEqual("PHM 1:1", m_filteredScp.ReferenceTextBox.Text); } /// ------------------------------------------------------------------------------------ /// <summary> /// Test that the reference gets resolved properly when the text box loses focus. /// </summary> /// ------------------------------------------------------------------------------------ [Test] public void ResolveReferenceOnLoseFocus() { m_ctrlOwner.Visible = true; m_scp.ReferenceTextBox.Focus(); m_scp.ReferenceTextBox.Text = "rev"; m_scp.DropDownButton.Focus(); Assert.AreEqual("REV 1:1", m_scp.ReferenceTextBox.Text); } /// ------------------------------------------------------------------------------------ /// <summary> /// Test that the text portion is all selected when the text box gains focus. /// </summary> /// ------------------------------------------------------------------------------------ [Test] public void TextAllSelectedOnFocus() { m_ctrlOwner.Visible = true; m_scp.DropDownButton.Focus(); m_scp.ReferenceTextBox.Text = "REV 1:1"; m_scp.ReferenceTextBox.Focus(); Assert.AreEqual(0, m_scp.ReferenceTextBox.SelectionStart); Assert.AreEqual(7, m_scp.ReferenceTextBox.SelectionLength); } /// ------------------------------------------------------------------------------------ /// <summary> /// Tests that all the books that are in the database are shown in the drop down list. /// </summary> /// ------------------------------------------------------------------------------------ [Test] public void VerifyBookCountForFilteredList() { m_filteredScp.SimulateDropDownButtonClick(); Assert.AreEqual(3, m_filteredScp.DropDownWindow.ButtonsShowing, "Incorrect number of books showing"); } /// ------------------------------------------------------------------------------------ /// <summary> /// Tests that all the books that are in the database are shown in the drop down list. /// </summary> /// ------------------------------------------------------------------------------------ [Test] public void FilteredListHasBooksInCanonicalOrder() { m_filteredScp.Initialize(new BCVRef(3, 3, 3), m_versification, new [] {4, 5, 3, 2}); Assert.AreEqual(4, m_filteredScp.BookLabels.Length); Assert.AreEqual(2, m_filteredScp.BookLabels[0].BookNum); Assert.AreEqual(3, m_filteredScp.BookLabels[1].BookNum); Assert.AreEqual(4, m_filteredScp.BookLabels[2].BookNum); Assert.AreEqual(5, m_filteredScp.BookLabels[3].BookNum); } /// ------------------------------------------------------------------------------------ /// <summary> /// Tests that all the books that are in the database are shown in the drop down list. /// </summary> /// ------------------------------------------------------------------------------------ [Test] public void FilteredListPreventsDuplicateBooks() { m_filteredScp.Initialize(new BCVRef(3, 3, 3), m_versification, new[] { 4, 3, 3, 4 }); Assert.AreEqual(2, m_filteredScp.BookLabels.Length); Assert.AreEqual(3, m_filteredScp.BookLabels[0].BookNum); Assert.AreEqual(4, m_filteredScp.BookLabels[1].BookNum); } /// ------------------------------------------------------------------------------------ /// <summary> /// Tests populating drop down control - this doesn't work well on build machine, so /// test has been marked as being "ByHand". /// </summary> /// ------------------------------------------------------------------------------------ [Test] [Category("ByHand")] public void VerifyDropDownContentWithInvalidDefault() { // Set control to really invalid reference. m_scp.Reference = "DAVID 100:100"; m_scp.SimulateDropDownButtonClick(); WaitForDropDownWindow(m_scp, 66); // Verify Genesis is the current and default book. Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue, "Incorrect Current Book Button"); Assert.AreEqual(1, m_scp.DropDownWindow.CurrentBook, "Incorrect Current Book"); Assert.AreEqual(ScrPassageDropDown.ListTypes.Books, m_scp.DropDownWindow.CurrentListType, "Incorrect List is showing"); Assert.AreEqual(66, m_scp.DropDownWindow.ButtonsShowing, "Incorrect number of books showing"); // Choose Deuteronomy and move to the chapter list. m_scp.DropDownWindow.SetCurrentButton(5); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter)); // Verify the contents of the passage control's text box. Assert.AreEqual("DEU 1:1", m_scp.ReferenceTextBox.Text.ToUpper()); // Verify that chapter 1 is current and default chapter. Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue, "Incorrect Current Chapter Button"); Assert.AreEqual(1, m_scp.DropDownWindow.CurrentChapter, "Incorrect Current Chapter"); Assert.AreEqual(ScrPassageDropDown.ListTypes.Chapters, m_scp.DropDownWindow.CurrentListType, "Incorrect List is showing"); // Should be 34 chapters showing Assert.AreEqual(34, m_scp.DropDownWindow.ButtonsShowing, "Incorrect number of chapters showing"); // Choose Chapter 17 and move to the verse list. m_scp.DropDownWindow.SetCurrentButton(17); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter)); // Verify the contents of the passage control's text box. Assert.AreEqual("DEU 17:1", m_scp.ReferenceTextBox.Text.ToUpper()); // Verify that verse 1 is current and default verse. Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue, "Incorrect Current Verse Button"); Assert.AreEqual(1, m_scp.DropDownWindow.CurrentVerse, "Incorrect Current Verse"); Assert.AreEqual(ScrPassageDropDown.ListTypes.Verses, m_scp.DropDownWindow.CurrentListType, "Incorrect List is showing"); // Should be 20 verses showing Assert.AreEqual(20, m_scp.DropDownWindow.ButtonsShowing, "Incorrect number of verses showing"); // Choose verse 13, press enter and verify the drop-down disappears. m_scp.DropDownWindow.SetCurrentButton(13); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.IsNull(m_scp.DropDownWindow, "Drop-down should not be visible"); // Verify the contents of the passage control's text box and it's reference object. Assert.AreEqual("DEU 17:13", m_scp.ReferenceTextBox.Text.ToUpper()); Assert.AreEqual("DEU 17:13", m_scp.Reference); Assert.AreEqual("DEU 17:13", m_scp.ScReference.AsString.ToUpper()); } /// ------------------------------------------------------------------------------------ /// <summary> /// Tests populating drop down control - this doesn't work well on build machine, so /// test has been marked as being "ByHand". /// </summary> /// ------------------------------------------------------------------------------------ [Test] [Category("ByHand")] public void VerifyEscapeBehavior() { // Set control to really invalid reference. m_scp.Reference = "DAVID 100:100"; m_scp.SimulateDropDownButtonClick(); WaitForDropDownWindow(m_scp, 66); // Move to chapter list and verify content in the passage control's text box. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.AreEqual("GEN 1:1", m_scp.ReferenceTextBox.Text.ToUpper()); // Move to verse list and verify content in the passage control's text box. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.AreEqual("GEN 1:1", m_scp.ReferenceTextBox.Text.ToUpper()); // Escape from the drop-down and verify that the drop-down goes away. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Escape)); Assert.IsNull(m_scp.DropDownWindow, "Drop-down should not be visible"); } /// ------------------------------------------------------------------------------------ /// <summary> /// Tests populating drop down control - this doesn't work well on build machine, so /// test has been marked as being "ByHand". /// </summary> /// ------------------------------------------------------------------------------------ [Test] [Category("ByHand")] public void VerifyClickingOutsideDropdownBehavior() { // Set control to really invalid reference. m_scp.Reference = "DAVID 100:100"; m_scp.SimulateDropDownButtonClick(); WaitForDropDownWindow(m_scp, 66); // Move to chapter list and verify content in the passage control's text box. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.AreEqual("GEN 1:1", m_scp.ReferenceTextBox.Text.ToUpper()); // Move to verse list and verify content in the passage control's text box. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.AreEqual("GEN 1:1", m_scp.ReferenceTextBox.Text.ToUpper()); // Close the drop-down and verify the control's text box has the reference that // was selected so far. m_scp.DropDownWindow.Close(); Assert.AreEqual("GEN 1:1", m_scp.ReferenceTextBox.Text.ToUpper()); Assert.IsNull(m_scp.DropDownWindow, "Drop-down should not be visible"); } /// ------------------------------------------------------------------------------------ /// <summary> /// Tests selecting books, chapters, and verses using the keyboard in the drop down /// control - this doesn't work well on build machine, so test has been marked as being /// "ByHand". /// </summary> /// ------------------------------------------------------------------------------------ [Test] [Category("ByHand")] public void VerifyKeyboardAcceleratorDropdownBehavior() { // Set control to really invalid reference. m_scp.Reference = "DAVID 100:100"; m_scp.SimulateDropDownButtonClick(); WaitForDropDownWindow(m_scp, 66); // Select a book using the keyboard. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Q)); Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.J)); Assert.AreEqual(6, m_scp.DropDownWindow.CurrentButtonValue); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.J)); Assert.AreEqual(7, m_scp.DropDownWindow.CurrentButtonValue); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.U)); Assert.AreEqual(7, m_scp.DropDownWindow.CurrentButtonValue); // Move to chapter list and verify content in the passage control's text box. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue); // Select a chapter using the keyboard. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D0)); Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D1)); Assert.AreEqual(10, m_scp.DropDownWindow.CurrentButtonValue); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D1)); Assert.AreEqual(11, m_scp.DropDownWindow.CurrentButtonValue); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D1)); Assert.AreEqual(12, m_scp.DropDownWindow.CurrentButtonValue); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D2)); Assert.AreEqual(20, m_scp.DropDownWindow.CurrentButtonValue); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D2)); Assert.AreEqual(21, m_scp.DropDownWindow.CurrentButtonValue); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Q)); Assert.AreEqual(21, m_scp.DropDownWindow.CurrentButtonValue); // Move to verse list and verify content in the passage control's text box. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue); // Select a verse using the keyboard. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D3)); Assert.AreEqual(3, m_scp.DropDownWindow.CurrentButtonValue); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D3)); Assert.AreEqual(3, m_scp.DropDownWindow.CurrentButtonValue); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D1)); Assert.AreEqual(10, m_scp.DropDownWindow.CurrentButtonValue); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D1)); Assert.AreEqual(11, m_scp.DropDownWindow.CurrentButtonValue); } /// ------------------------------------------------------------------------------------ /// <summary> /// Tests selecting books, chapters, and verses using the keyboard in the drop down /// control - this doesn't work well on build machine, so test has been marked as being /// "ByHand". /// </summary> /// ------------------------------------------------------------------------------------ [Test] [Ignore("Not sure that it's really desirable to have the selected book and chapter be" + " retained if the user cancels or clicks away. Anyway, it doesn't actually behave that way now.")] public void VerifyreferenceIsRetainedWhenDropdownCloses() { // Set control to really invalid reference. m_scp.Reference = "DAVID 100:100"; m_scp.SimulateDropDownButtonClick(); WaitForDropDownWindow(m_scp, 66); // Select a book using the keyboard. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.J)); Assert.AreEqual(6, m_scp.DropDownWindow.CurrentButtonValue); m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.J)); Assert.AreEqual(7, m_scp.DropDownWindow.CurrentButtonValue); // Move to chapter list and verify content in the passage control's text box. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue); // Select a chapter using the keyboard. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D1)); Assert.AreEqual(10, m_scp.DropDownWindow.CurrentButtonValue); // Move to verse list and verify content in the passage control's text box. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter)); Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue); // Select a verse using the keyboard. m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D3)); Assert.AreEqual(3, m_scp.DropDownWindow.CurrentButtonValue); // Close the drop-down and verify the control's text box has the reference that // was selected so far. m_scp.DropDownWindow.Close(); Assert.AreEqual("JDG 10:3", m_scp.ReferenceTextBox.Text.ToUpper()); Assert.IsNull(m_scp.DropDownWindow, "Drop-down should not be visible"); } #endregion #region helper methods /// ------------------------------------------------------------------------------------ /// <summary> /// Tries the DoEvents a few times to give the DropDownWindow a chance to become active. /// Tests were occassionally failing due to a null DropDownWindow reference. /// </summary> /// ------------------------------------------------------------------------------------ private static void WaitForDropDownWindow(DummyScrPassageControl spc, int expectedCount) { int i = 0; do { Application.DoEvents(); if (spc.DropDownWindow != null && spc.DropDownWindow.Menu != null && spc.DropDownWindow.Menu.MenuItems.Count == expectedCount) break; i++; } while (i < 20); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using TheBigCatProject.Server.Areas.HelpPage.ModelDescriptions; using TheBigCatProject.Server.Areas.HelpPage.Models; namespace TheBigCatProject.Server.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; 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.Deploy.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCloudDeployClientTest { [xunit::FactAttribute] public void GetDeliveryPipelineRequestObject() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDeliveryPipelineRequest request = new GetDeliveryPipelineRequest { DeliveryPipelineName = DeliveryPipelineName.FromProjectLocationDeliveryPipeline("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]"), }; DeliveryPipeline expectedResponse = new DeliveryPipeline { DeliveryPipelineName = DeliveryPipelineName.FromProjectLocationDeliveryPipeline("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SerialPipeline = new SerialPipeline(), Etag = "etage8ad7218", Condition = new PipelineCondition(), }; mockGrpcClient.Setup(x => x.GetDeliveryPipeline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); DeliveryPipeline response = client.GetDeliveryPipeline(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDeliveryPipelineRequestObjectAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDeliveryPipelineRequest request = new GetDeliveryPipelineRequest { DeliveryPipelineName = DeliveryPipelineName.FromProjectLocationDeliveryPipeline("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]"), }; DeliveryPipeline expectedResponse = new DeliveryPipeline { DeliveryPipelineName = DeliveryPipelineName.FromProjectLocationDeliveryPipeline("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SerialPipeline = new SerialPipeline(), Etag = "etage8ad7218", Condition = new PipelineCondition(), }; mockGrpcClient.Setup(x => x.GetDeliveryPipelineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DeliveryPipeline>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); DeliveryPipeline responseCallSettings = await client.GetDeliveryPipelineAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); DeliveryPipeline responseCancellationToken = await client.GetDeliveryPipelineAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDeliveryPipeline() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDeliveryPipelineRequest request = new GetDeliveryPipelineRequest { DeliveryPipelineName = DeliveryPipelineName.FromProjectLocationDeliveryPipeline("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]"), }; DeliveryPipeline expectedResponse = new DeliveryPipeline { DeliveryPipelineName = DeliveryPipelineName.FromProjectLocationDeliveryPipeline("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SerialPipeline = new SerialPipeline(), Etag = "etage8ad7218", Condition = new PipelineCondition(), }; mockGrpcClient.Setup(x => x.GetDeliveryPipeline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); DeliveryPipeline response = client.GetDeliveryPipeline(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDeliveryPipelineAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDeliveryPipelineRequest request = new GetDeliveryPipelineRequest { DeliveryPipelineName = DeliveryPipelineName.FromProjectLocationDeliveryPipeline("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]"), }; DeliveryPipeline expectedResponse = new DeliveryPipeline { DeliveryPipelineName = DeliveryPipelineName.FromProjectLocationDeliveryPipeline("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SerialPipeline = new SerialPipeline(), Etag = "etage8ad7218", Condition = new PipelineCondition(), }; mockGrpcClient.Setup(x => x.GetDeliveryPipelineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DeliveryPipeline>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); DeliveryPipeline responseCallSettings = await client.GetDeliveryPipelineAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); DeliveryPipeline responseCancellationToken = await client.GetDeliveryPipelineAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDeliveryPipelineResourceNames() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDeliveryPipelineRequest request = new GetDeliveryPipelineRequest { DeliveryPipelineName = DeliveryPipelineName.FromProjectLocationDeliveryPipeline("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]"), }; DeliveryPipeline expectedResponse = new DeliveryPipeline { DeliveryPipelineName = DeliveryPipelineName.FromProjectLocationDeliveryPipeline("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SerialPipeline = new SerialPipeline(), Etag = "etage8ad7218", Condition = new PipelineCondition(), }; mockGrpcClient.Setup(x => x.GetDeliveryPipeline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); DeliveryPipeline response = client.GetDeliveryPipeline(request.DeliveryPipelineName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDeliveryPipelineResourceNamesAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDeliveryPipelineRequest request = new GetDeliveryPipelineRequest { DeliveryPipelineName = DeliveryPipelineName.FromProjectLocationDeliveryPipeline("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]"), }; DeliveryPipeline expectedResponse = new DeliveryPipeline { DeliveryPipelineName = DeliveryPipelineName.FromProjectLocationDeliveryPipeline("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SerialPipeline = new SerialPipeline(), Etag = "etage8ad7218", Condition = new PipelineCondition(), }; mockGrpcClient.Setup(x => x.GetDeliveryPipelineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DeliveryPipeline>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); DeliveryPipeline responseCallSettings = await client.GetDeliveryPipelineAsync(request.DeliveryPipelineName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); DeliveryPipeline responseCancellationToken = await client.GetDeliveryPipelineAsync(request.DeliveryPipelineName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTargetRequestObject() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTargetRequest request = new GetTargetRequest { TargetName = TargetName.FromProjectLocationTarget("[PROJECT]", "[LOCATION]", "[TARGET]"), }; Target expectedResponse = new Target { TargetName = TargetName.FromProjectLocationTarget("[PROJECT]", "[LOCATION]", "[TARGET]"), TargetId = "target_id16dfe255", Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", RequireApproval = false, Gke = new GkeCluster(), ExecutionConfigs = { new ExecutionConfig(), }, }; mockGrpcClient.Setup(x => x.GetTarget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Target response = client.GetTarget(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTargetRequestObjectAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTargetRequest request = new GetTargetRequest { TargetName = TargetName.FromProjectLocationTarget("[PROJECT]", "[LOCATION]", "[TARGET]"), }; Target expectedResponse = new Target { TargetName = TargetName.FromProjectLocationTarget("[PROJECT]", "[LOCATION]", "[TARGET]"), TargetId = "target_id16dfe255", Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", RequireApproval = false, Gke = new GkeCluster(), ExecutionConfigs = { new ExecutionConfig(), }, }; mockGrpcClient.Setup(x => x.GetTargetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Target>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Target responseCallSettings = await client.GetTargetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Target responseCancellationToken = await client.GetTargetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTarget() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTargetRequest request = new GetTargetRequest { TargetName = TargetName.FromProjectLocationTarget("[PROJECT]", "[LOCATION]", "[TARGET]"), }; Target expectedResponse = new Target { TargetName = TargetName.FromProjectLocationTarget("[PROJECT]", "[LOCATION]", "[TARGET]"), TargetId = "target_id16dfe255", Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", RequireApproval = false, Gke = new GkeCluster(), ExecutionConfigs = { new ExecutionConfig(), }, }; mockGrpcClient.Setup(x => x.GetTarget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Target response = client.GetTarget(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTargetAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTargetRequest request = new GetTargetRequest { TargetName = TargetName.FromProjectLocationTarget("[PROJECT]", "[LOCATION]", "[TARGET]"), }; Target expectedResponse = new Target { TargetName = TargetName.FromProjectLocationTarget("[PROJECT]", "[LOCATION]", "[TARGET]"), TargetId = "target_id16dfe255", Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", RequireApproval = false, Gke = new GkeCluster(), ExecutionConfigs = { new ExecutionConfig(), }, }; mockGrpcClient.Setup(x => x.GetTargetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Target>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Target responseCallSettings = await client.GetTargetAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Target responseCancellationToken = await client.GetTargetAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTargetResourceNames() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTargetRequest request = new GetTargetRequest { TargetName = TargetName.FromProjectLocationTarget("[PROJECT]", "[LOCATION]", "[TARGET]"), }; Target expectedResponse = new Target { TargetName = TargetName.FromProjectLocationTarget("[PROJECT]", "[LOCATION]", "[TARGET]"), TargetId = "target_id16dfe255", Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", RequireApproval = false, Gke = new GkeCluster(), ExecutionConfigs = { new ExecutionConfig(), }, }; mockGrpcClient.Setup(x => x.GetTarget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Target response = client.GetTarget(request.TargetName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTargetResourceNamesAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTargetRequest request = new GetTargetRequest { TargetName = TargetName.FromProjectLocationTarget("[PROJECT]", "[LOCATION]", "[TARGET]"), }; Target expectedResponse = new Target { TargetName = TargetName.FromProjectLocationTarget("[PROJECT]", "[LOCATION]", "[TARGET]"), TargetId = "target_id16dfe255", Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", RequireApproval = false, Gke = new GkeCluster(), ExecutionConfigs = { new ExecutionConfig(), }, }; mockGrpcClient.Setup(x => x.GetTargetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Target>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Target responseCallSettings = await client.GetTargetAsync(request.TargetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Target responseCancellationToken = await client.GetTargetAsync(request.TargetName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetReleaseRequestObject() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetReleaseRequest request = new GetReleaseRequest { ReleaseName = ReleaseName.FromProjectLocationDeliveryPipelineRelease("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]"), }; Release expectedResponse = new Release { ReleaseName = ReleaseName.FromProjectLocationDeliveryPipelineRelease("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), RenderStartTime = new wkt::Timestamp(), RenderEndTime = new wkt::Timestamp(), SkaffoldConfigPath = "skaffold_config_path583ece19", BuildArtifacts = { new BuildArtifact(), }, DeliveryPipelineSnapshot = new DeliveryPipeline(), TargetSnapshots = { new Target(), }, RenderState = Release.Types.RenderState.Failed, Etag = "etage8ad7218", SkaffoldConfigUri = "skaffold_config_urif0232045", SkaffoldVersion = "skaffold_versionc9ef9e12", TargetArtifacts = { { "key8a0b6e3c", new TargetArtifact() }, }, TargetRenders = { { "key8a0b6e3c", new Release.Types.TargetRender() }, }, }; mockGrpcClient.Setup(x => x.GetRelease(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Release response = client.GetRelease(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetReleaseRequestObjectAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetReleaseRequest request = new GetReleaseRequest { ReleaseName = ReleaseName.FromProjectLocationDeliveryPipelineRelease("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]"), }; Release expectedResponse = new Release { ReleaseName = ReleaseName.FromProjectLocationDeliveryPipelineRelease("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), RenderStartTime = new wkt::Timestamp(), RenderEndTime = new wkt::Timestamp(), SkaffoldConfigPath = "skaffold_config_path583ece19", BuildArtifacts = { new BuildArtifact(), }, DeliveryPipelineSnapshot = new DeliveryPipeline(), TargetSnapshots = { new Target(), }, RenderState = Release.Types.RenderState.Failed, Etag = "etage8ad7218", SkaffoldConfigUri = "skaffold_config_urif0232045", SkaffoldVersion = "skaffold_versionc9ef9e12", TargetArtifacts = { { "key8a0b6e3c", new TargetArtifact() }, }, TargetRenders = { { "key8a0b6e3c", new Release.Types.TargetRender() }, }, }; mockGrpcClient.Setup(x => x.GetReleaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Release>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Release responseCallSettings = await client.GetReleaseAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Release responseCancellationToken = await client.GetReleaseAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRelease() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetReleaseRequest request = new GetReleaseRequest { ReleaseName = ReleaseName.FromProjectLocationDeliveryPipelineRelease("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]"), }; Release expectedResponse = new Release { ReleaseName = ReleaseName.FromProjectLocationDeliveryPipelineRelease("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), RenderStartTime = new wkt::Timestamp(), RenderEndTime = new wkt::Timestamp(), SkaffoldConfigPath = "skaffold_config_path583ece19", BuildArtifacts = { new BuildArtifact(), }, DeliveryPipelineSnapshot = new DeliveryPipeline(), TargetSnapshots = { new Target(), }, RenderState = Release.Types.RenderState.Failed, Etag = "etage8ad7218", SkaffoldConfigUri = "skaffold_config_urif0232045", SkaffoldVersion = "skaffold_versionc9ef9e12", TargetArtifacts = { { "key8a0b6e3c", new TargetArtifact() }, }, TargetRenders = { { "key8a0b6e3c", new Release.Types.TargetRender() }, }, }; mockGrpcClient.Setup(x => x.GetRelease(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Release response = client.GetRelease(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetReleaseAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetReleaseRequest request = new GetReleaseRequest { ReleaseName = ReleaseName.FromProjectLocationDeliveryPipelineRelease("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]"), }; Release expectedResponse = new Release { ReleaseName = ReleaseName.FromProjectLocationDeliveryPipelineRelease("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), RenderStartTime = new wkt::Timestamp(), RenderEndTime = new wkt::Timestamp(), SkaffoldConfigPath = "skaffold_config_path583ece19", BuildArtifacts = { new BuildArtifact(), }, DeliveryPipelineSnapshot = new DeliveryPipeline(), TargetSnapshots = { new Target(), }, RenderState = Release.Types.RenderState.Failed, Etag = "etage8ad7218", SkaffoldConfigUri = "skaffold_config_urif0232045", SkaffoldVersion = "skaffold_versionc9ef9e12", TargetArtifacts = { { "key8a0b6e3c", new TargetArtifact() }, }, TargetRenders = { { "key8a0b6e3c", new Release.Types.TargetRender() }, }, }; mockGrpcClient.Setup(x => x.GetReleaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Release>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Release responseCallSettings = await client.GetReleaseAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Release responseCancellationToken = await client.GetReleaseAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetReleaseResourceNames() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetReleaseRequest request = new GetReleaseRequest { ReleaseName = ReleaseName.FromProjectLocationDeliveryPipelineRelease("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]"), }; Release expectedResponse = new Release { ReleaseName = ReleaseName.FromProjectLocationDeliveryPipelineRelease("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), RenderStartTime = new wkt::Timestamp(), RenderEndTime = new wkt::Timestamp(), SkaffoldConfigPath = "skaffold_config_path583ece19", BuildArtifacts = { new BuildArtifact(), }, DeliveryPipelineSnapshot = new DeliveryPipeline(), TargetSnapshots = { new Target(), }, RenderState = Release.Types.RenderState.Failed, Etag = "etage8ad7218", SkaffoldConfigUri = "skaffold_config_urif0232045", SkaffoldVersion = "skaffold_versionc9ef9e12", TargetArtifacts = { { "key8a0b6e3c", new TargetArtifact() }, }, TargetRenders = { { "key8a0b6e3c", new Release.Types.TargetRender() }, }, }; mockGrpcClient.Setup(x => x.GetRelease(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Release response = client.GetRelease(request.ReleaseName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetReleaseResourceNamesAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetReleaseRequest request = new GetReleaseRequest { ReleaseName = ReleaseName.FromProjectLocationDeliveryPipelineRelease("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]"), }; Release expectedResponse = new Release { ReleaseName = ReleaseName.FromProjectLocationDeliveryPipelineRelease("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), RenderStartTime = new wkt::Timestamp(), RenderEndTime = new wkt::Timestamp(), SkaffoldConfigPath = "skaffold_config_path583ece19", BuildArtifacts = { new BuildArtifact(), }, DeliveryPipelineSnapshot = new DeliveryPipeline(), TargetSnapshots = { new Target(), }, RenderState = Release.Types.RenderState.Failed, Etag = "etage8ad7218", SkaffoldConfigUri = "skaffold_config_urif0232045", SkaffoldVersion = "skaffold_versionc9ef9e12", TargetArtifacts = { { "key8a0b6e3c", new TargetArtifact() }, }, TargetRenders = { { "key8a0b6e3c", new Release.Types.TargetRender() }, }, }; mockGrpcClient.Setup(x => x.GetReleaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Release>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Release responseCallSettings = await client.GetReleaseAsync(request.ReleaseName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Release responseCancellationToken = await client.GetReleaseAsync(request.ReleaseName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ApproveRolloutRequestObject() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ApproveRolloutRequest request = new ApproveRolloutRequest { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), Approved = true, }; ApproveRolloutResponse expectedResponse = new ApproveRolloutResponse { }; mockGrpcClient.Setup(x => x.ApproveRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); ApproveRolloutResponse response = client.ApproveRollout(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ApproveRolloutRequestObjectAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ApproveRolloutRequest request = new ApproveRolloutRequest { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), Approved = true, }; ApproveRolloutResponse expectedResponse = new ApproveRolloutResponse { }; mockGrpcClient.Setup(x => x.ApproveRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ApproveRolloutResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); ApproveRolloutResponse responseCallSettings = await client.ApproveRolloutAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ApproveRolloutResponse responseCancellationToken = await client.ApproveRolloutAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ApproveRollout() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ApproveRolloutRequest request = new ApproveRolloutRequest { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), }; ApproveRolloutResponse expectedResponse = new ApproveRolloutResponse { }; mockGrpcClient.Setup(x => x.ApproveRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); ApproveRolloutResponse response = client.ApproveRollout(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ApproveRolloutAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ApproveRolloutRequest request = new ApproveRolloutRequest { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), }; ApproveRolloutResponse expectedResponse = new ApproveRolloutResponse { }; mockGrpcClient.Setup(x => x.ApproveRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ApproveRolloutResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); ApproveRolloutResponse responseCallSettings = await client.ApproveRolloutAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ApproveRolloutResponse responseCancellationToken = await client.ApproveRolloutAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ApproveRolloutResourceNames() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ApproveRolloutRequest request = new ApproveRolloutRequest { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), }; ApproveRolloutResponse expectedResponse = new ApproveRolloutResponse { }; mockGrpcClient.Setup(x => x.ApproveRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); ApproveRolloutResponse response = client.ApproveRollout(request.RolloutName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ApproveRolloutResourceNamesAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ApproveRolloutRequest request = new ApproveRolloutRequest { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), }; ApproveRolloutResponse expectedResponse = new ApproveRolloutResponse { }; mockGrpcClient.Setup(x => x.ApproveRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ApproveRolloutResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); ApproveRolloutResponse responseCallSettings = await client.ApproveRolloutAsync(request.RolloutName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ApproveRolloutResponse responseCancellationToken = await client.ApproveRolloutAsync(request.RolloutName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRolloutRequestObject() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRolloutRequest request = new GetRolloutRequest { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), }; Rollout expectedResponse = new Rollout { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproveTime = new wkt::Timestamp(), EnqueueTime = new wkt::Timestamp(), DeployStartTime = new wkt::Timestamp(), DeployEndTime = new wkt::Timestamp(), ApprovalState = Rollout.Types.ApprovalState.Rejected, State = Rollout.Types.State.Pending, FailureReason = "failure_reasonb933af24", Etag = "etage8ad7218", DeployingBuildAsBuildName = BuildName.FromProjectLocationBuild("[PROJECT]", "[LOCATION]", "[BUILD]"), TargetId = "target_id16dfe255", }; mockGrpcClient.Setup(x => x.GetRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Rollout response = client.GetRollout(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRolloutRequestObjectAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRolloutRequest request = new GetRolloutRequest { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), }; Rollout expectedResponse = new Rollout { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproveTime = new wkt::Timestamp(), EnqueueTime = new wkt::Timestamp(), DeployStartTime = new wkt::Timestamp(), DeployEndTime = new wkt::Timestamp(), ApprovalState = Rollout.Types.ApprovalState.Rejected, State = Rollout.Types.State.Pending, FailureReason = "failure_reasonb933af24", Etag = "etage8ad7218", DeployingBuildAsBuildName = BuildName.FromProjectLocationBuild("[PROJECT]", "[LOCATION]", "[BUILD]"), TargetId = "target_id16dfe255", }; mockGrpcClient.Setup(x => x.GetRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Rollout>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Rollout responseCallSettings = await client.GetRolloutAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Rollout responseCancellationToken = await client.GetRolloutAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRollout() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRolloutRequest request = new GetRolloutRequest { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), }; Rollout expectedResponse = new Rollout { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproveTime = new wkt::Timestamp(), EnqueueTime = new wkt::Timestamp(), DeployStartTime = new wkt::Timestamp(), DeployEndTime = new wkt::Timestamp(), ApprovalState = Rollout.Types.ApprovalState.Rejected, State = Rollout.Types.State.Pending, FailureReason = "failure_reasonb933af24", Etag = "etage8ad7218", DeployingBuildAsBuildName = BuildName.FromProjectLocationBuild("[PROJECT]", "[LOCATION]", "[BUILD]"), TargetId = "target_id16dfe255", }; mockGrpcClient.Setup(x => x.GetRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Rollout response = client.GetRollout(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRolloutAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRolloutRequest request = new GetRolloutRequest { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), }; Rollout expectedResponse = new Rollout { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproveTime = new wkt::Timestamp(), EnqueueTime = new wkt::Timestamp(), DeployStartTime = new wkt::Timestamp(), DeployEndTime = new wkt::Timestamp(), ApprovalState = Rollout.Types.ApprovalState.Rejected, State = Rollout.Types.State.Pending, FailureReason = "failure_reasonb933af24", Etag = "etage8ad7218", DeployingBuildAsBuildName = BuildName.FromProjectLocationBuild("[PROJECT]", "[LOCATION]", "[BUILD]"), TargetId = "target_id16dfe255", }; mockGrpcClient.Setup(x => x.GetRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Rollout>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Rollout responseCallSettings = await client.GetRolloutAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Rollout responseCancellationToken = await client.GetRolloutAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRolloutResourceNames() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRolloutRequest request = new GetRolloutRequest { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), }; Rollout expectedResponse = new Rollout { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproveTime = new wkt::Timestamp(), EnqueueTime = new wkt::Timestamp(), DeployStartTime = new wkt::Timestamp(), DeployEndTime = new wkt::Timestamp(), ApprovalState = Rollout.Types.ApprovalState.Rejected, State = Rollout.Types.State.Pending, FailureReason = "failure_reasonb933af24", Etag = "etage8ad7218", DeployingBuildAsBuildName = BuildName.FromProjectLocationBuild("[PROJECT]", "[LOCATION]", "[BUILD]"), TargetId = "target_id16dfe255", }; mockGrpcClient.Setup(x => x.GetRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Rollout response = client.GetRollout(request.RolloutName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRolloutResourceNamesAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRolloutRequest request = new GetRolloutRequest { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), }; Rollout expectedResponse = new Rollout { RolloutName = RolloutName.FromProjectLocationDeliveryPipelineReleaseRollout("[PROJECT]", "[LOCATION]", "[DELIVERY_PIPELINE]", "[RELEASE]", "[ROLLOUT]"), Uid = "uida2d37198", Description = "description2cf9da67", Annotations = { { "key8a0b6e3c", "value60c16320" }, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, CreateTime = new wkt::Timestamp(), ApproveTime = new wkt::Timestamp(), EnqueueTime = new wkt::Timestamp(), DeployStartTime = new wkt::Timestamp(), DeployEndTime = new wkt::Timestamp(), ApprovalState = Rollout.Types.ApprovalState.Rejected, State = Rollout.Types.State.Pending, FailureReason = "failure_reasonb933af24", Etag = "etage8ad7218", DeployingBuildAsBuildName = BuildName.FromProjectLocationBuild("[PROJECT]", "[LOCATION]", "[BUILD]"), TargetId = "target_id16dfe255", }; mockGrpcClient.Setup(x => x.GetRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Rollout>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Rollout responseCallSettings = await client.GetRolloutAsync(request.RolloutName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Rollout responseCancellationToken = await client.GetRolloutAsync(request.RolloutName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetConfigRequestObject() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetConfigRequest request = new GetConfigRequest { ConfigName = ConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; Config expectedResponse = new Config { ConfigName = ConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"), SupportedVersions = { new SkaffoldVersion(), }, DefaultSkaffoldVersion = "default_skaffold_versioncb9ecadf", }; mockGrpcClient.Setup(x => x.GetConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Config response = client.GetConfig(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetConfigRequestObjectAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetConfigRequest request = new GetConfigRequest { ConfigName = ConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; Config expectedResponse = new Config { ConfigName = ConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"), SupportedVersions = { new SkaffoldVersion(), }, DefaultSkaffoldVersion = "default_skaffold_versioncb9ecadf", }; mockGrpcClient.Setup(x => x.GetConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Config>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Config responseCallSettings = await client.GetConfigAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Config responseCancellationToken = await client.GetConfigAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetConfig() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetConfigRequest request = new GetConfigRequest { ConfigName = ConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; Config expectedResponse = new Config { ConfigName = ConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"), SupportedVersions = { new SkaffoldVersion(), }, DefaultSkaffoldVersion = "default_skaffold_versioncb9ecadf", }; mockGrpcClient.Setup(x => x.GetConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Config response = client.GetConfig(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetConfigAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetConfigRequest request = new GetConfigRequest { ConfigName = ConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; Config expectedResponse = new Config { ConfigName = ConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"), SupportedVersions = { new SkaffoldVersion(), }, DefaultSkaffoldVersion = "default_skaffold_versioncb9ecadf", }; mockGrpcClient.Setup(x => x.GetConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Config>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Config responseCallSettings = await client.GetConfigAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Config responseCancellationToken = await client.GetConfigAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetConfigResourceNames() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetConfigRequest request = new GetConfigRequest { ConfigName = ConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; Config expectedResponse = new Config { ConfigName = ConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"), SupportedVersions = { new SkaffoldVersion(), }, DefaultSkaffoldVersion = "default_skaffold_versioncb9ecadf", }; mockGrpcClient.Setup(x => x.GetConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Config response = client.GetConfig(request.ConfigName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetConfigResourceNamesAsync() { moq::Mock<CloudDeploy.CloudDeployClient> mockGrpcClient = new moq::Mock<CloudDeploy.CloudDeployClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetConfigRequest request = new GetConfigRequest { ConfigName = ConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; Config expectedResponse = new Config { ConfigName = ConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"), SupportedVersions = { new SkaffoldVersion(), }, DefaultSkaffoldVersion = "default_skaffold_versioncb9ecadf", }; mockGrpcClient.Setup(x => x.GetConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Config>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CloudDeployClient client = new CloudDeployClientImpl(mockGrpcClient.Object, null); Config responseCallSettings = await client.GetConfigAsync(request.ConfigName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Config responseCancellationToken = await client.GetConfigAsync(request.ConfigName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// 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.Globalization; namespace System.Net.Http.Headers { public class StringWithQualityHeaderValue : ICloneable { private string _value; private double? _quality; public string Value { get { return _value; } } public double? Quality { get { return _quality; } } public StringWithQualityHeaderValue(string value) { HeaderUtilities.CheckValidToken(value, nameof(value)); _value = value; } public StringWithQualityHeaderValue(string value, double quality) { HeaderUtilities.CheckValidToken(value, nameof(value)); if ((quality < 0) || (quality > 1)) { throw new ArgumentOutOfRangeException(nameof(quality)); } _value = value; _quality = quality; } private StringWithQualityHeaderValue(StringWithQualityHeaderValue source) { Debug.Assert(source != null); _value = source._value; _quality = source._quality; } private StringWithQualityHeaderValue() { } public override string ToString() { if (_quality.HasValue) { return _value + "; q=" + _quality.Value.ToString("0.0##", NumberFormatInfo.InvariantInfo); } return _value; } public override bool Equals(object obj) { StringWithQualityHeaderValue other = obj as StringWithQualityHeaderValue; if (other == null) { return false; } if (!string.Equals(_value, other._value, StringComparison.OrdinalIgnoreCase)) { return false; } if (_quality.HasValue) { // Note that we don't consider double.Epsilon here. We really consider two values equal if they're // actually equal. This makes sure that we also get the same hashcode for two values considered equal // by Equals(). return other._quality.HasValue && (_quality.Value == other._quality.Value); } // If we don't have a quality value, then 'other' must also have no quality assigned in order to be // considered equal. return !other._quality.HasValue; } public override int GetHashCode() { int result = StringComparer.OrdinalIgnoreCase.GetHashCode(_value); if (_quality.HasValue) { result = result ^ _quality.Value.GetHashCode(); } return result; } public static StringWithQualityHeaderValue Parse(string input) { int index = 0; return (StringWithQualityHeaderValue)GenericHeaderParser.SingleValueStringWithQualityParser.ParseValue( input, null, ref index); } public static bool TryParse(string input, out StringWithQualityHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (GenericHeaderParser.SingleValueStringWithQualityParser.TryParseValue( input, null, ref index, out output)) { parsedValue = (StringWithQualityHeaderValue)output; return true; } return false; } internal static int GetStringWithQualityLength(string input, int startIndex, out object parsedValue) { Debug.Assert(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Parse the value string: <value> in '<value>; q=<quality>' int valueLength = HttpRuleParser.GetTokenLength(input, startIndex); if (valueLength == 0) { return 0; } StringWithQualityHeaderValue result = new StringWithQualityHeaderValue(); result._value = input.Substring(startIndex, valueLength); int current = startIndex + valueLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); if ((current == input.Length) || (input[current] != ';')) { parsedValue = result; return current - startIndex; // we have a valid token, but no quality. } current++; // skip ';' separator current = current + HttpRuleParser.GetWhitespaceLength(input, current); // If we found a ';' separator, it must be followed by a quality information if (!TryReadQuality(input, result, ref current)) { return 0; } parsedValue = result; return current - startIndex; } private static bool TryReadQuality(string input, StringWithQualityHeaderValue result, ref int index) { int current = index; // See if we have a quality value by looking for "q" if ((current == input.Length) || ((input[current] != 'q') && (input[current] != 'Q'))) { return false; } current++; // skip 'q' identifier current = current + HttpRuleParser.GetWhitespaceLength(input, current); // If we found "q" it must be followed by "=" if ((current == input.Length) || (input[current] != '=')) { return false; } current++; // skip '=' separator current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (current == input.Length) { return false; } int qualityLength = HttpRuleParser.GetNumberLength(input, current, true); if (qualityLength == 0) { return false; } double quality = 0; if (!double.TryParse(input.AsSpan(current, qualityLength), NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out quality)) { return false; } if ((quality < 0) || (quality > 1)) { return false; } result._quality = quality; current = current + qualityLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); index = current; return true; } object ICloneable.Clone() { return new StringWithQualityHeaderValue(this); } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.IO; using Adxstudio.Xrm.Web; using Adxstudio.Xrm.Web.Mvc; using Adxstudio.Xrm.Resources; using Microsoft.Xrm.Portal.Web; using Microsoft.Xrm.Sdk; namespace Adxstudio.Xrm.Forums { public class HtmlForumPostSubmission : IForumPostSubmission { public HtmlForumPostSubmission(string name, string htmlContent, DateTime postedOn, IForumAuthor author) { if (string.IsNullOrEmpty(name)) throw new ArgumentException("Value can't be null or empty.", "name"); if (postedOn.Kind != DateTimeKind.Utc) throw new ArgumentException("Value must be UTC.", "postedOn"); if (author == null) throw new ArgumentNullException("author"); Name = name; Content = SafeHtml.SafeHtmSanitizer.GetSafeHtml(htmlContent ?? string.Empty); PostedOn = postedOn; Author = author; Attachments = new List<IForumPostAttachment>(); } public IEnumerable<IForumPostAttachmentInfo> AttachmentInfo { get { return new IForumPostAttachmentInfo[] { }; } } public ICollection<IForumPostAttachment> Attachments { get; private set; } public DateTime PostedOn { get; private set; } public EntityReference ThreadEntity { get; private set; } EntityReference IPortalViewEntity.EntityReference { get { return null; } } public string Url { get { return null; } } public string Content { get; private set; } public bool CanEdit { get { return false; } } public ApplicationPath DeletePath { get { return null; } } public ApplicationPath EditPath { get { return null; } } public Entity Entity { get { return null; } } public int HelpfulVoteCount { get { return 0; } } public bool IsAnswer { get; set; } public bool CanMarkAsAnswer { get; set; } public string Name { get; private set; } public IForumThread Thread { get; set; } public string Description { get { return string.Empty; } } public bool Editable { get { return false; } } public IForumAuthor Author { get; private set; } EntityReference IForumPostInfo.EntityReference { get { return null; } } public IPortalViewAttribute GetAttribute(string attributeLogicalName) { throw new NotSupportedException(); } } public interface IForumPostAttachment { byte[] Content { get; } string ContentType { get; } string Name { get; } } public class ForumPostAttachment : IForumPostAttachment { public ForumPostAttachment(string name, string contentType, byte[] content) { if (name == null) throw new ArgumentNullException("name"); if (content == null) throw new ArgumentNullException("content"); Name = Path.GetFileName(name); ContentType = contentType; Content = content; } public byte[] Content { get; private set; } public string ContentType { get; private set; } public string Name { get; private set; } } public class HtmlForumPostUpdate : IForumPostSubmission { private readonly EntityReference _entityReference; public HtmlForumPostUpdate(EntityReference entityReference, string name = null, string htmlContent = null) { if (entityReference == null) throw new ArgumentNullException("entityReference"); _entityReference = entityReference; Name = name; Content = htmlContent == null ? null : SafeHtml.SafeHtmSanitizer.GetSafeHtml(htmlContent); Attachments = new List<IForumPostAttachment>(); } public IEnumerable<IForumPostAttachmentInfo> AttachmentInfo { get { return new IForumPostAttachmentInfo[] { }; } } public ICollection<IForumPostAttachment> Attachments { get; private set; } public DateTime PostedOn { get { return default(DateTime); } } public EntityReference ThreadEntity { get { return null; } } EntityReference IPortalViewEntity.EntityReference { get { return _entityReference; } } public string Url { get { return null; } } public string Content { get; private set; } public bool CanEdit { get { return false; } } public ApplicationPath DeletePath { get { return null; } } public ApplicationPath EditPath { get { return null; } } public Entity Entity { get { return null; } } public int HelpfulVoteCount { get { return 0; } } public bool IsAnswer { get { return false; } } public bool CanMarkAsAnswer { get { return false; } } public string Name { get; private set; } public IForumThread Thread { get { return null; } } public string Description { get { return string.Empty; } } public bool Editable { get { return false; } } public IForumAuthor Author { get { return null; } } EntityReference IForumPostInfo.EntityReference { get { return _entityReference; } } public IPortalViewAttribute GetAttribute(string attributeLogicalName) { throw new NotSupportedException(); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.CodeGeneration; using Orleans.Runtime; using Orleans.Serialization; namespace Orleans { internal class InvokableObjectManager : IDisposable { private readonly CancellationTokenSource disposed = new CancellationTokenSource(); private readonly ConcurrentDictionary<GuidId, LocalObjectData> localObjects = new ConcurrentDictionary<GuidId, LocalObjectData>(); private readonly IRuntimeClient runtimeClient; private readonly ILogger logger; private readonly SerializationManager serializationManager; private readonly Func<object, Task> dispatchFunc; public InvokableObjectManager(IRuntimeClient runtimeClient, SerializationManager serializationManager, ILogger<InvokableObjectManager> logger) { this.runtimeClient = runtimeClient; this.serializationManager = serializationManager; this.logger = logger; this.dispatchFunc = o => this.LocalObjectMessagePumpAsync((LocalObjectData) o); } public bool TryRegister(IAddressable obj, GuidId objectId, IGrainMethodInvoker invoker) { return this.localObjects.TryAdd(objectId, new LocalObjectData(obj, objectId, invoker)); } public bool TryDeregister(GuidId objectId) { return this.localObjects.TryRemove(objectId, out LocalObjectData ignored); } public void Dispatch(Message message) { GuidId observerId = message.TargetObserverId; if (observerId == null) { this.logger.Error( ErrorCode.ProxyClient_OGC_TargetNotFound_2, string.Format("Did not find TargetObserverId header in the message = {0}. A request message to a client is expected to have an observerId.", message)); return; } if (this.localObjects.TryGetValue(observerId, out var objectData)) { this.Invoke(objectData, message); } else { this.logger.Error( ErrorCode.ProxyClient_OGC_TargetNotFound, String.Format( "Unexpected target grain in request: {0}. Message={1}", message.TargetGrain, message)); } } private void Invoke(LocalObjectData objectData, Message message) { var obj = (IAddressable)objectData.LocalObject.Target; if (obj == null) { //// Remove from the dictionary record for the garbage collected object? But now we won't be able to detect invalid dispatch IDs anymore. this.logger.Warn( ErrorCode.Runtime_Error_100162, string.Format( "Object associated with Observer ID {0} has been garbage collected. Deleting object reference and unregistering it. Message = {1}", objectData.ObserverId, message)); // Try to remove. If it's not there, we don't care. this.TryDeregister(objectData.ObserverId); return; } bool start; lock (objectData.Messages) { objectData.Messages.Enqueue(message); start = !objectData.Running; objectData.Running = true; } if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace($"InvokeLocalObjectAsync {message} start {start}"); if (start) { // we want to ensure that the message pump operates asynchronously // with respect to the current thread. see // http://channel9.msdn.com/Events/TechEd/Europe/2013/DEV-B317#fbid=aIWUq0ssW74 // at position 54:45. // // according to the information posted at: // http://stackoverflow.com/questions/12245935/is-task-factory-startnew-guaranteed-to-use-another-thread-than-the-calling-thr // this idiom is dependent upon the a TaskScheduler not implementing the // override QueueTask as task inlining (as opposed to queueing). this seems // implausible to the author, since none of the .NET schedulers do this and // it is considered bad form (the OrleansTaskScheduler does not do this). // // if, for some reason this doesn't hold true, we can guarantee what we // want by passing a placeholder continuation token into Task.StartNew() // instead. i.e.: // // return Task.StartNew(() => ..., new CancellationToken()); // We pass these options to Task.Factory.StartNew as they make the call identical // to Task.Run. See: https://blogs.msdn.microsoft.com/pfxteam/2011/10/24/task-run-vs-task-factory-startnew/ Task.Factory.StartNew( this.dispatchFunc, objectData, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Ignore(); } } private async Task LocalObjectMessagePumpAsync(LocalObjectData objectData) { while (true) { try { Message message; lock (objectData.Messages) { if (objectData.Messages.Count == 0) { objectData.Running = false; break; } message = objectData.Messages.Dequeue(); } if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Invoke)) continue; RequestContextExtensions.Import(message.RequestContextData); var request = (InvokeMethodRequest)message.GetDeserializedBody(this.serializationManager); var targetOb = (IAddressable)objectData.LocalObject.Target; object resultObject = null; Exception caught = null; try { // exceptions thrown within this scope are not considered to be thrown from user code // and not from runtime code. var resultPromise = objectData.Invoker.Invoke(targetOb, request); if (resultPromise != null) // it will be null for one way messages { resultObject = await resultPromise; } } catch (Exception exc) { // the exception needs to be reported in the log or propagated back to the caller. caught = exc; } if (caught != null) this.ReportException(message, caught); else if (message.Direction != Message.Directions.OneWay) this.SendResponseAsync(message, resultObject); } catch (Exception) { // ignore, keep looping. } } } private static bool ExpireMessageIfExpired(Message message, MessagingStatisticsGroup.Phase phase) { if (message.IsExpired) { message.DropExpiredMessage(phase); return true; } return false; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void SendResponseAsync(Message message, object resultObject) { if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Respond)) { return; } object deepCopy; try { // we're expected to notify the caller if the deep copy failed. deepCopy = this.serializationManager.DeepCopy(resultObject); } catch (Exception exc2) { this.runtimeClient.SendResponse(message, Response.ExceptionResponse(exc2)); this.logger.Warn( ErrorCode.ProxyClient_OGC_SendResponseFailed, "Exception trying to send a response.", exc2); return; } // the deep-copy succeeded. this.runtimeClient.SendResponse(message, new Response(deepCopy)); return; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void ReportException(Message message, Exception exception) { var request = (InvokeMethodRequest)message.GetDeserializedBody(this.serializationManager); switch (message.Direction) { case Message.Directions.OneWay: { this.logger.Error( ErrorCode.ProxyClient_OGC_UnhandledExceptionInOneWayInvoke, String.Format( "Exception during invocation of notification method {0}, interface {1}. Ignoring exception because this is a one way request.", request.MethodId, request.InterfaceId), exception); break; } case Message.Directions.Request: { Exception deepCopy = null; try { // we're expected to notify the caller if the deep copy failed. deepCopy = (Exception)this.serializationManager.DeepCopy(exception); } catch (Exception ex2) { this.runtimeClient.SendResponse(message, Response.ExceptionResponse(ex2)); this.logger.Warn( ErrorCode.ProxyClient_OGC_SendExceptionResponseFailed, "Exception trying to send an exception response", ex2); return; } // the deep-copy succeeded. var response = Response.ExceptionResponse(deepCopy); this.runtimeClient.SendResponse(message, response); break; } default: throw new InvalidOperationException($"Unrecognized direction for message {message}, request {request}, which resulted in exception: {exception}"); } } public class LocalObjectData { internal WeakReference LocalObject { get; } internal IGrainMethodInvoker Invoker { get; } internal GuidId ObserverId { get; } internal Queue<Message> Messages { get; } internal bool Running { get; set; } internal LocalObjectData(IAddressable obj, GuidId observerId, IGrainMethodInvoker invoker) { this.LocalObject = new WeakReference(obj); this.ObserverId = observerId; this.Invoker = invoker; this.Messages = new Queue<Message>(); this.Running = false; } } public void Dispose() { var tokenSource = this.disposed; Utils.SafeExecute(() => tokenSource?.Cancel(false)); Utils.SafeExecute(() => tokenSource?.Dispose()); } } }
using System; using System.Collections.Generic; using System.Linq; using Avalonia.Interactivity; using Avalonia.VisualTree; namespace Avalonia.Input { /// <summary> /// Handles access keys for a window. /// </summary> public class AccessKeyHandler : IAccessKeyHandler { /// <summary> /// Defines the AccessKeyPressed attached event. /// </summary> public static readonly RoutedEvent<RoutedEventArgs> AccessKeyPressedEvent = RoutedEvent.Register<RoutedEventArgs>( "AccessKeyPressed", RoutingStrategies.Bubble, typeof(AccessKeyHandler)); /// <summary> /// The registered access keys. /// </summary> private readonly List<Tuple<string, IInputElement>> _registered = new List<Tuple<string, IInputElement>>(); /// <summary> /// The window to which the handler belongs. /// </summary> private IInputRoot? _owner; /// <summary> /// Whether access keys are currently being shown; /// </summary> private bool _showingAccessKeys; /// <summary> /// Whether to ignore the Alt KeyUp event. /// </summary> private bool _ignoreAltUp; /// <summary> /// Whether the AltKey is down. /// </summary> private bool _altIsDown; /// <summary> /// Element to restore following AltKey taking focus. /// </summary> private IInputElement? _restoreFocusElement; /// <summary> /// The window's main menu. /// </summary> private IMainMenu? _mainMenu; /// <summary> /// Gets or sets the window's main menu. /// </summary> public IMainMenu? MainMenu { get => _mainMenu; set { if (_mainMenu != null) { _mainMenu.MenuClosed -= MainMenuClosed; } _mainMenu = value; if (_mainMenu != null) { _mainMenu.MenuClosed += MainMenuClosed; } } } /// <summary> /// Sets the owner of the access key handler. /// </summary> /// <param name="owner">The owner.</param> /// <remarks> /// This method can only be called once, typically by the owner itself on creation. /// </remarks> public void SetOwner(IInputRoot owner) { if (_owner != null) { throw new InvalidOperationException("AccessKeyHandler owner has already been set."); } _owner = owner ?? throw new ArgumentNullException(nameof(owner)); _owner.AddHandler(InputElement.KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); _owner.AddHandler(InputElement.KeyDownEvent, OnKeyDown, RoutingStrategies.Bubble); _owner.AddHandler(InputElement.KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); _owner.AddHandler(InputElement.PointerPressedEvent, OnPreviewPointerPressed, RoutingStrategies.Tunnel); } /// <summary> /// Registers an input element to be associated with an access key. /// </summary> /// <param name="accessKey">The access key.</param> /// <param name="element">The input element.</param> public void Register(char accessKey, IInputElement element) { var existing = _registered.FirstOrDefault(x => x.Item2 == element); if (existing != null) { _registered.Remove(existing); } _registered.Add(Tuple.Create(accessKey.ToString().ToUpper(), element)); } /// <summary> /// Unregisters the access keys associated with the input element. /// </summary> /// <param name="element">The input element.</param> public void Unregister(IInputElement element) { foreach (var i in _registered.Where(x => x.Item2 == element).ToList()) { _registered.Remove(i); } } /// <summary> /// Called when a key is pressed in the owner window. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void OnPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.LeftAlt || e.Key == Key.RightAlt) { _altIsDown = true; if (MainMenu == null || !MainMenu.IsOpen) { // TODO: Use FocusScopes to store the current element and restore it when context menu is closed. // Save currently focused input element. _restoreFocusElement = FocusManager.Instance.Current; // When Alt is pressed without a main menu, or with a closed main menu, show // access key markers in the window (i.e. "_File"). _owner!.ShowAccessKeys = _showingAccessKeys = true; } else { // If the Alt key is pressed and the main menu is open, close the main menu. CloseMenu(); _ignoreAltUp = true; _restoreFocusElement?.Focus(); _restoreFocusElement = null; e.Handled = true; } } else if (_altIsDown) { _ignoreAltUp = true; } } /// <summary> /// Called when a key is pressed in the owner window. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void OnKeyDown(object sender, KeyEventArgs e) { bool menuIsOpen = MainMenu?.IsOpen == true; if (e.KeyModifiers.HasAllFlags(KeyModifiers.Alt) || menuIsOpen) { // If any other key is pressed with the Alt key held down, or the main menu is open, // find all controls who have registered that access key. var text = e.Key.ToString().ToUpper(); var matches = _registered .Where(x => x.Item1 == text && x.Item2.IsEffectivelyVisible) .Select(x => x.Item2); // If the menu is open, only match controls in the menu's visual tree. if (menuIsOpen) { matches = matches.Where(x => MainMenu.IsVisualAncestorOf(x)); } var match = matches.FirstOrDefault(); // If there was a match, raise the AccessKeyPressed event on it. if (match != null) { match.RaiseEvent(new RoutedEventArgs(AccessKeyPressedEvent)); e.Handled = true; } } } /// <summary> /// Handles the Alt/F10 keys being released in the window. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void OnPreviewKeyUp(object sender, KeyEventArgs e) { switch (e.Key) { case Key.LeftAlt: case Key.RightAlt: _altIsDown = false; if (_ignoreAltUp) { _ignoreAltUp = false; } else if (_showingAccessKeys && MainMenu != null) { MainMenu.Open(); e.Handled = true; } break; } } /// <summary> /// Handles pointer presses in the window. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void OnPreviewPointerPressed(object sender, PointerEventArgs e) { if (_showingAccessKeys) { _owner!.ShowAccessKeys = false; } } /// <summary> /// Closes the <see cref="MainMenu"/> and performs other bookeeping. /// </summary> private void CloseMenu() { MainMenu!.Close(); _owner!.ShowAccessKeys = _showingAccessKeys = false; } private void MainMenuClosed(object sender, EventArgs e) { _owner!.ShowAccessKeys = 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 Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace Internal.IL.Stubs { internal struct ArrayMethodILEmitter { private ArrayMethod _method; private TypeDesc _elementType; private int _rank; private ILToken _helperFieldToken; private ILEmitter _emitter; private ArrayMethodILEmitter(ArrayMethod method) { Debug.Assert(method.Kind != ArrayMethodKind.Address, "Should be " + nameof(ArrayMethodKind.AddressWithHiddenArg)); _method = method; ArrayType arrayType = (ArrayType)method.OwningType; _rank = arrayType.Rank; _elementType = arrayType.ElementType; _emitter = new ILEmitter(); // This helper field is needed to generate proper GC tracking. There is no direct way // to create interior pointer. _helperFieldToken = _emitter.NewToken(_method.Context.GetWellKnownType(WellKnownType.Object).GetKnownField("m_pEEType")); } private void EmitLoadInteriorAddress(ILCodeStream codeStream, int offset) { codeStream.EmitLdArg(0); // this codeStream.Emit(ILOpcode.ldflda, _helperFieldToken); codeStream.EmitLdc(offset); codeStream.Emit(ILOpcode.add); } private MethodIL EmitIL() { switch (_method.Kind) { case ArrayMethodKind.Get: case ArrayMethodKind.Set: case ArrayMethodKind.AddressWithHiddenArg: EmitILForAccessor(); break; case ArrayMethodKind.Ctor: // .ctor is implemented as a JIT helper and the JIT shouldn't be asking for the IL. default: // Asking for anything else is invalid. throw new InvalidOperationException(); } return _emitter.Link(_method); } public static MethodIL EmitIL(ArrayMethod arrayMethod) { return new ArrayMethodILEmitter(arrayMethod).EmitIL(); } private void EmitILForAccessor() { Debug.Assert(_method.OwningType.IsMdArray); var codeStream = _emitter.NewCodeStream(); var context = _method.Context; var int32Type = context.GetWellKnownType(WellKnownType.Int32); var totalLocalNum = _emitter.NewLocal(int32Type); var lengthLocalNum = _emitter.NewLocal(int32Type); int pointerSize = context.Target.PointerSize; int argStartOffset = _method.Kind == ArrayMethodKind.AddressWithHiddenArg ? 2 : 1; var rangeExceptionLabel = _emitter.NewCodeLabel(); ILCodeLabel typeMismatchExceptionLabel = null; if (!_elementType.IsValueType) { // Type check if (_method.Kind == ArrayMethodKind.Set) { MethodDesc checkArrayStore = context.SystemModule.GetKnownType("System.Runtime", "RuntimeImports").GetKnownMethod("RhCheckArrayStore", null); codeStream.EmitLdArg(0); codeStream.EmitLdArg(_rank + argStartOffset); codeStream.Emit(ILOpcode.call, _emitter.NewToken(checkArrayStore)); } else if (_method.Kind == ArrayMethodKind.AddressWithHiddenArg) { TypeDesc objectType = context.GetWellKnownType(WellKnownType.Object); TypeDesc eetypePtrType = context.SystemModule.GetKnownType("System", "EETypePtr"); typeMismatchExceptionLabel = _emitter.NewCodeLabel(); ILLocalVariable thisEEType = _emitter.NewLocal(eetypePtrType); // EETypePtr actualElementType = this.EETypePtr.ArrayElementType; codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.call, _emitter.NewToken(objectType.GetKnownMethod("get_EETypePtr", null))); codeStream.EmitStLoc(thisEEType); codeStream.EmitLdLoca(thisEEType); codeStream.Emit(ILOpcode.call, _emitter.NewToken(eetypePtrType.GetKnownMethod("get_ArrayElementType", null))); // EETypePtr expectedElementType = hiddenArg.ArrayElementType; codeStream.EmitLdArga(1); codeStream.Emit(ILOpcode.call, _emitter.NewToken(eetypePtrType.GetKnownMethod("get_ArrayElementType", null))); // if (expectedElementType != actualElementType) // ThrowHelpers.ThrowArrayTypeMismatchException(); codeStream.Emit(ILOpcode.call, _emitter.NewToken(eetypePtrType.GetKnownMethod("op_Equality", null))); codeStream.Emit(ILOpcode.brfalse, typeMismatchExceptionLabel); } } for (int i = 0; i < _rank; i++) { // The first two fields are EEType pointer and total length. Lengths for each dimension follows. int lengthOffset = (2 * pointerSize + i * int32Type.GetElementSize()); EmitLoadInteriorAddress(codeStream, lengthOffset); codeStream.Emit(ILOpcode.ldind_i4); codeStream.EmitStLoc(lengthLocalNum); codeStream.EmitLdArg(i + argStartOffset); // Compare with length codeStream.Emit(ILOpcode.dup); codeStream.EmitLdLoc(lengthLocalNum); codeStream.Emit(ILOpcode.bge_un, rangeExceptionLabel); // Add to the running total if we have one already if (i > 0) { codeStream.EmitLdLoc(totalLocalNum); codeStream.EmitLdLoc(lengthLocalNum); codeStream.Emit(ILOpcode.mul); codeStream.Emit(ILOpcode.add); } codeStream.EmitStLoc(totalLocalNum); } // Compute element offset // TODO: This leaves unused space for lower bounds to match CoreCLR... int firstElementOffset = (2 * pointerSize + 2 * _rank * int32Type.GetElementSize()); EmitLoadInteriorAddress(codeStream, firstElementOffset); codeStream.EmitLdLoc(totalLocalNum); int elementSize = _elementType.GetElementSize(); if (elementSize != 1) { codeStream.EmitLdc(elementSize); codeStream.Emit(ILOpcode.mul); } codeStream.Emit(ILOpcode.add); switch (_method.Kind) { case ArrayMethodKind.Get: codeStream.Emit(ILOpcode.ldobj, _emitter.NewToken(_elementType)); break; case ArrayMethodKind.Set: codeStream.EmitLdArg(_rank + argStartOffset); codeStream.Emit(ILOpcode.stobj, _emitter.NewToken(_elementType)); break; case ArrayMethodKind.AddressWithHiddenArg: break; } codeStream.Emit(ILOpcode.ret); codeStream.EmitLdc(0); codeStream.EmitLabel(rangeExceptionLabel); // Assumes that there is one "int" pushed on the stack codeStream.Emit(ILOpcode.pop); MethodDesc throwHelper = context.GetHelperEntryPoint("ThrowHelpers", "ThrowIndexOutOfRangeException"); codeStream.EmitCallThrowHelper(_emitter, throwHelper); if (typeMismatchExceptionLabel != null) { codeStream.EmitLabel(typeMismatchExceptionLabel); codeStream.EmitCallThrowHelper(_emitter, context.GetHelperEntryPoint("ThrowHelpers", "ThrowArrayTypeMismatchException")); } } } }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Apis.Upload; using Google.Cloud.ClientTesting; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using Xunit; namespace Google.Cloud.Storage.V1.IntegrationTests { [Collection(nameof(StorageFixture))] public class UrlSignerTest { private static readonly TimeSpan _duration = TimeSpan.FromSeconds(5); private readonly StorageFixture _fixture; public UrlSignerTest(StorageFixture fixture) { _fixture = fixture; _fixture.RegisterDelayTests(this); } private static string GetTestName([CallerMemberName] string methodName = null) { return $"{nameof(UrlSignerTest)}.{methodName}"; } [Fact] public async Task DeleteTest() => await _fixture.FinishDelayTest(GetTestName()); private void DeleteTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = IdGenerator.FromGuid(); string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign(bucket, name, duration, HttpMethod.Delete); // Upload an object which can be deleted with the URL. await _fixture.Client.UploadObjectAsync(bucket, name, "", new MemoryStream(_fixture.SmallContent)); // Verify that the URL works initially. var response = await _fixture.HttpClient.DeleteAsync(url); await VerifyResponseAsync(response); var obj = await _fixture.Client.ListObjectsAsync(bucket, name).FirstOrDefault(o => o.Name == name); Assert.Null(obj); // Restore the object. await _fixture.Client.UploadObjectAsync(bucket, name, "", new MemoryStream(_fixture.SmallContent)); }, afterDelay: async () => { // Verify that the URL no longer works. var response = await _fixture.HttpClient.DeleteAsync(url); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); var obj = await _fixture.Client.ListObjectsAsync(bucket, name).FirstOrDefault(o => o.Name == name); Assert.NotNull(obj); // Cleanup await _fixture.Client.DeleteObjectAsync(bucket, name); }); } [Fact] public async Task GetTest() => await _fixture.FinishDelayTest(GetTestName()); private void GetTest_InitDelayTest() { string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign(_fixture.ReadBucket, _fixture.SmallObject, duration); // Verify that the URL works initially. var response = await _fixture.HttpClient.GetAsync(url); var result = await response.Content.ReadAsByteArrayAsync(); AssertContentEqual(_fixture.SmallContent, result); }, afterDelay: async () => { // Verify that the URL no longer works. var response = await _fixture.HttpClient.GetAsync(url); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }); } [Fact] public async Task GetBucketTest() => await _fixture.FinishDelayTest(GetTestName()); private void GetBucketTest_InitDelayTest() { var bucket = _fixture.ReadBucket; string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign(bucket, null, duration); // Verify that the URL works initially. var response = await _fixture.HttpClient.GetAsync(url); var result = await response.Content.ReadAsStringAsync(); var document = XDocument.Parse(result); var ns = document.Root.GetDefaultNamespace(); var keys = document.Root.Elements(ns + "Contents").Select(contents => contents.Element(ns + "Key").Value).ToList(); var objectNames = await _fixture.Client.ListObjectsAsync(bucket, null).Select(o => o.Name).ToList(); Assert.Equal(objectNames, keys); }, afterDelay: async () => { // Verify that the URL no longer works. var response = await _fixture.HttpClient.GetAsync(url); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }); } [Fact] public async Task GetObjectWithSpacesTest() => await _fixture.FinishDelayTest(GetTestName()); private void GetObjectWithSpacesTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = IdGenerator.FromGuid() + " with spaces"; var content = _fixture.SmallContent; string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { _fixture.Client.UploadObject(bucket, name, null, new MemoryStream(content)); url = _fixture.UrlSigner.Sign(bucket, name, duration); // Verify that the URL works initially. var response = await _fixture.HttpClient.GetAsync(url); await VerifyResponseAsync(response); var result = await response.Content.ReadAsByteArrayAsync(); AssertContentEqual(content, result); }, afterDelay: async () => { // Verify that the URL no longer works. var response = await _fixture.HttpClient.GetAsync(url); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }); } [Fact] public async Task GetWithCustomerSuppliedEncryptionKeysTest() => await _fixture.FinishDelayTest(GetTestName()); private void GetWithCustomerSuppliedEncryptionKeysTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = IdGenerator.FromGuid(); var content = _fixture.SmallContent; string url = null; EncryptionKey key = EncryptionKey.Generate(); Func<HttpRequestMessage> createGetRequest = () => { var request = new HttpRequestMessage { Method = HttpMethod.Get }; key.ModifyRequest(request); return request; }; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { var encryptingClient = StorageClient.Create(encryptionKey: key); encryptingClient.UploadObject(bucket, name, "application/octet-stream", new MemoryStream(content)); var request = createGetRequest(); url = _fixture.UrlSigner.Sign(bucket, name, duration, request); request.RequestUri = new Uri(url); // Verify that the URL works initially. var response = await _fixture.HttpClient.SendAsync(request); var result = await response.Content.ReadAsByteArrayAsync(); AssertContentEqual(content, result); }, afterDelay: async () => { // Verify that the URL no longer works. var request = createGetRequest(); request.RequestUri = new Uri(url); var response = await _fixture.HttpClient.SendAsync(request); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); // Cleanup await _fixture.Client.DeleteObjectAsync(bucket, name); }); } [Fact] public async Task GetNoExpirationTest() { var url = _fixture.UrlSigner.Sign(_fixture.ReadBucket, _fixture.SmallObject, expiration: null); // Verify that the URL works. var response = await _fixture.HttpClient.GetAsync(url); var result = await response.Content.ReadAsByteArrayAsync(); AssertContentEqual(_fixture.SmallContent, result); } [Fact] public async Task GetWithCustomHeadersTest() => await _fixture.FinishDelayTest(GetTestName()); private void GetWithCustomHeadersTest_InitDelayTest() { string url = null; Func<HttpRequestMessage> createRequest = () => new HttpRequestMessage() { Method = HttpMethod.Get, Headers = { { "x-goog-foo", "xy\r\n z" }, { "x-goog-bar", " 12345 " }, { "x-goog-foo", new [] { "A B C", "def" } } } }; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { var request = createRequest(); url = _fixture.UrlSigner.Sign( _fixture.ReadBucket, _fixture.SmallObject, duration, request); request.RequestUri = new Uri(url); // Verify that the URL works initially. var response = await _fixture.HttpClient.SendAsync(request); var result = await response.Content.ReadAsByteArrayAsync(); AssertContentEqual(_fixture.SmallContent, result); }, afterDelay: async () => { // Verify that the URL no longer works. var request = createRequest(); request.RequestUri = new Uri(url); var response = await _fixture.HttpClient.SendAsync(request); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }); } [Fact] public async Task HeadTest() => await _fixture.FinishDelayTest(GetTestName()); private void HeadTest_InitDelayTest() { Func<HttpRequestMessage> createRequest = null; string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign( _fixture.ReadBucket, _fixture.SmallObject, duration, HttpMethod.Head); createRequest = () => new HttpRequestMessage(HttpMethod.Head, url); // Verify that the URL works initially. var response = await _fixture.HttpClient.SendAsync(createRequest()); await VerifyResponseAsync(response); }, afterDelay: async () => { // Verify that the URL no longer works. var response = await _fixture.HttpClient.SendAsync(createRequest()); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }); } [Fact] public async Task HeadWithGetMethodSignedURLTest() => await _fixture.FinishDelayTest(GetTestName()); private void HeadWithGetMethodSignedURLTest_InitDelayTest() { Func<HttpRequestMessage> createRequest = null; string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign( _fixture.ReadBucket, _fixture.SmallObject, duration, HttpMethod.Get); createRequest = () => new HttpRequestMessage(HttpMethod.Head, url); // Verify that the URL works initially. var response = await _fixture.HttpClient.SendAsync(createRequest()); await VerifyResponseAsync(response); }, afterDelay: async () => { // Verify that the URL no longer works. var response = await _fixture.HttpClient.SendAsync(createRequest()); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); }); } [Fact] public async Task PutTest() => await _fixture.FinishDelayTest(GetTestName()); private void PutTest_InitDelayTest() { Func<Task> expireAction1 = null; Func<Task> expireAction2 = null; Func<Task> expireAction3 = null; Func<Task> expireAction4 = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { expireAction1 = await PutTestHelper(duration, useContentMD5: false, useContentType: false); expireAction2 = await PutTestHelper(duration, useContentMD5: true, useContentType: false); expireAction3 = await PutTestHelper(duration, useContentMD5: false, useContentType: true); expireAction4 = await PutTestHelper(duration, useContentMD5: true, useContentType: true); }, afterDelay: async () => { await expireAction1(); await expireAction2(); await expireAction3(); await expireAction4(); }); } private async Task<Func<Task>> PutTestHelper(TimeSpan duration, bool useContentMD5, bool useContentType) { var bucket = _fixture.SingleVersionBucket; var name = IdGenerator.FromGuid(); var data = _fixture.SmallContent; Func<ByteArrayContent> createPutContent = () => { var putContent = new ByteArrayContent(data); if (useContentMD5) { using (var md5 = MD5.Create()) { putContent.Headers.ContentMD5 = md5.ComputeHash(data); } } if (useContentType) { putContent.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); } return putContent; }; var content = createPutContent(); var url = _fixture.UrlSigner.Sign( bucket, name, duration, HttpMethod.Put, contentHeaders: content.Headers.ToDictionary(h => h.Key, h => h.Value)); // Verify that the URL works initially. var response = await _fixture.HttpClient.PutAsync(url, content); await VerifyResponseAsync(response); var result = new MemoryStream(); await _fixture.Client.DownloadObjectAsync(bucket, name, result); AssertContentEqual(data, result.ToArray()); // Reset the state and wait until the URL expires. await _fixture.Client.DeleteObjectAsync(bucket, name); return async () => { // Verify that the URL no longer works. content = createPutContent(); response = await _fixture.HttpClient.PutAsync(url, content); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); var obj = await _fixture.Client.ListObjectsAsync(bucket, name).FirstOrDefault(o => o.Name == name); Assert.Null(obj); }; } [Fact] public async Task PutWithCustomerSuppliedEncryptionKeysTest() => await _fixture.FinishDelayTest(GetTestName()); private void PutWithCustomerSuppliedEncryptionKeysTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = IdGenerator.FromGuid(); var content = _fixture.SmallContent; string url = null; EncryptionKey key = EncryptionKey.Generate(); Func<HttpRequestMessage> createPutRequest = () => { var request = new HttpRequestMessage { Method = HttpMethod.Put, Content = new ByteArrayContent(content) }; key.ModifyRequest(request); return request; }; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { var request = createPutRequest(); url = _fixture.UrlSigner.Sign(bucket, name, duration, request); // Verify that the URL works initially. request.RequestUri = new Uri(url); var response = await _fixture.HttpClient.SendAsync(request); await VerifyResponseAsync(response); // Make sure the encryption succeeded. var downloadedContent = new MemoryStream(); await Assert.ThrowsAsync<GoogleApiException>( () => _fixture.Client.DownloadObjectAsync(bucket, name, downloadedContent)); await _fixture.Client.DownloadObjectAsync(bucket, name, downloadedContent, new DownloadObjectOptions { EncryptionKey = key }); AssertContentEqual(content, downloadedContent.ToArray()); }, afterDelay: async () => { // Verify that the URL no longer works. var request = createPutRequest(); request.RequestUri = new Uri(url); var response = await _fixture.HttpClient.SendAsync(request); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); // Cleanup await _fixture.Client.DeleteObjectAsync(bucket, name); }); } [Fact] public async Task PutWithCustomHeadersTest() => await _fixture.FinishDelayTest(GetTestName()); private void PutWithCustomHeadersTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = IdGenerator.FromGuid(); var content = _fixture.SmallContent; string url = null; Func<HttpRequestMessage> createRequest = () => { using (var md5 = MD5.Create()) { return new HttpRequestMessage() { Content = new ByteArrayContent(content) { Headers = { { "Content-MD5", Convert.ToBase64String(md5.ComputeHash(content)) }, { "Content-Type", "text/plain" }, { "x-goog-z-content-foo", "val1" }, { "x-goog-a-content-bar", "val2" }, { "x-goog-foo", new [] { "val3", "val4" } } } }, Method = HttpMethod.Put, Headers = { { "x-goog-foo2", "xy\r\n z" }, { "x-goog-bar", " 12345 " }, { "x-goog-foo2", new [] { "A B C", "def" } } } }; } }; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { var request = createRequest(); url = _fixture.UrlSigner.Sign(bucket, name, duration, request); request.RequestUri = new Uri(url); // Verify that the URL works initially. var response = await _fixture.HttpClient.SendAsync(request); await VerifyResponseAsync(response); var result = new MemoryStream(); await _fixture.Client.DownloadObjectAsync(bucket, name, result); AssertContentEqual(_fixture.SmallContent, result.ToArray()); // Reset the state. await _fixture.Client.DeleteObjectAsync(bucket, name); }, afterDelay: async () => { // Verify that the URL no longer works. var request = createRequest(); request.RequestUri = new Uri(url); var response = await _fixture.HttpClient.SendAsync(request); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); var obj = await _fixture.Client.ListObjectsAsync(bucket, name).FirstOrDefault(o => o.Name == name); Assert.Null(obj); }); } [Fact] public async Task ResumableUploadTest() => await _fixture.FinishDelayTest(GetTestName()); private void ResumableUploadTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = IdGenerator.FromGuid(); var content = _fixture.SmallContent; string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign(bucket, name, duration, UrlSigner.ResumableHttpMethod); // Verify that the URL works initially. var uploader = SignedUrlResumableUpload.Create(url, new MemoryStream(content)); var progress = await uploader.UploadAsync(); Assert.Equal(UploadStatus.Completed, progress.Status); var result = new MemoryStream(); await _fixture.Client.DownloadObjectAsync(bucket, name, result); AssertContentEqual(content, result.ToArray()); // Reset the state. await _fixture.Client.DeleteObjectAsync(bucket, name); }, afterDelay: async () => { var uploader = SignedUrlResumableUpload.Create(url, new MemoryStream(content)); // Verify that the URL no longer works. var progress = await uploader.UploadAsync(); Assert.Equal(UploadStatus.Failed, progress.Status); Assert.IsType<GoogleApiException>(progress.Exception); var obj = await _fixture.Client.ListObjectsAsync(bucket, name).FirstOrDefault(o => o.Name == name); Assert.Null(obj); }); } [Fact] public async Task ResumableUploadResumeTest() => await _fixture.FinishDelayTest(GetTestName()); private void ResumableUploadResumeTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = IdGenerator.FromGuid(); var content = _fixture.SmallContent; string url = null; _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign(bucket, name, duration, UrlSigner.ResumableHttpMethod); var sessionUri = await SignedUrlResumableUpload.InitiateSessionAsync(url); // Verify that the URL works initially. var uploader = ResumableUpload.CreateFromUploadUri(sessionUri, new MemoryStream(content)); var progress = await uploader.ResumeAsync(sessionUri); Assert.Null(progress.Exception); Assert.Equal(UploadStatus.Completed, progress.Status); var result = new MemoryStream(); await _fixture.Client.DownloadObjectAsync(bucket, name, result); AssertContentEqual(content, result.ToArray()); // Reset the state. await _fixture.Client.DeleteObjectAsync(bucket, name); }, afterDelay: async () => { // Verify that the URL no longer works. await Assert.ThrowsAsync<GoogleApiException>(() => SignedUrlResumableUpload.InitiateSessionAsync(url)); var obj = await _fixture.Client.ListObjectsAsync(bucket, name).FirstOrDefault(o => o.Name == name); Assert.Null(obj); }); } [Fact] public async Task ResumableUploadWithCustomerSuppliedEncryptionKeysTest() => await _fixture.FinishDelayTest(GetTestName()); private void ResumableUploadWithCustomerSuppliedEncryptionKeysTest_InitDelayTest() { var bucket = _fixture.SingleVersionBucket; var name = IdGenerator.FromGuid(); var content = _fixture.SmallContent; string url = null; EncryptionKey key = EncryptionKey.Generate(); _fixture.RegisterDelayTest(_duration, beforeDelay: async duration => { url = _fixture.UrlSigner.Sign( bucket, name, duration, UrlSigner.ResumableHttpMethod, requestHeaders: new Dictionary<string, IEnumerable<string>> { { "x-goog-encryption-algorithm", new [] { "AES256" } } }); // Verify that the URL works initially. var uploader = SignedUrlResumableUpload.Create( url, new MemoryStream(content), new ResumableUploadOptions { ModifySessionInitiationRequest = key.ModifyRequest }); var progress = await uploader.UploadAsync(); Assert.Null(progress.Exception); Assert.Equal(UploadStatus.Completed, progress.Status); // Make sure the encryption succeeded. var downloadedData = new MemoryStream(); await Assert.ThrowsAsync<GoogleApiException>( () => _fixture.Client.DownloadObjectAsync(bucket, name, downloadedData)); await _fixture.Client.DownloadObjectAsync(bucket, name, downloadedData, new DownloadObjectOptions { EncryptionKey = key }); AssertContentEqual(content, downloadedData.ToArray()); }, afterDelay: async () => { var uploader = SignedUrlResumableUpload.Create( url, new MemoryStream(content), new ResumableUploadOptions { ModifySessionInitiationRequest = key.ModifyRequest }); // Verify that the URL no longer works. var progress = await uploader.UploadAsync(); Assert.Equal(UploadStatus.Failed, progress.Status); Assert.IsType<GoogleApiException>(progress.Exception); }); } private static async Task VerifyResponseAsync(HttpResponseMessage response) { if (!response.IsSuccessStatusCode) { // This will automatically fail, but gives more information about the failure cause than // simply asserting that IsSuccessStatusCode is true. Assert.Null(await response.Content.ReadAsStringAsync()); } } private static void AssertContentEqual(byte[] expected, byte[] actual) { Assert.NotNull(actual); // Use the actual content string as the failure message so mis-matches are not truncated to 5 bytes in the build logs. Assert.True(expected.SequenceEqual(actual), $"Content did not match at {DateTimeOffset.UtcNow:s}. Actual content:\n{Encoding.UTF8.GetString(actual)}"); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// BackupEnginesOperations operations. /// </summary> internal partial class BackupEnginesOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IBackupEnginesOperations { /// <summary> /// Initializes a new instance of the BackupEnginesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal BackupEnginesOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Backup management servers registered to Recovery Services Vault. Returns a /// pageable list of servers. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='skipToken'> /// skipToken Filter. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<BackupEngineBaseResource>>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery<BMSBackupEngineQueryObject> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<BMSBackupEngineQueryObject>), string skipToken = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (vaultName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-06-01"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("skipToken", skipToken); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupEngines").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (skipToken != null) { _queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<BackupEngineBaseResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<BackupEngineBaseResource>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Backup management servers registered to Recovery Services Vault. Returns a /// pageable list of servers. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<BackupEngineBaseResource>>> GetNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<BackupEngineBaseResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<BackupEngineBaseResource>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql { /// <summary> /// Represents all the operations for operating on Azure SQL Job Accounts. /// Contains operations to: Create, Retrieve, Update, and Delete Job /// Accounts /// </summary> internal partial class JobAccountOperations : IServiceOperations<SqlManagementClient>, IJobAccountOperations { /// <summary> /// Initializes a new instance of the JobAccountOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal JobAccountOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Begins creating a new Azure SQL Job Account or updating an existing /// Azure SQL Job Account. To determine the status of the operation /// call GetJobAccountOperationStatus. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be created or /// updated. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Job /// Account. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public async Task<JobAccountOperationResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string serverName, string jobAccountName, JobAccountCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (jobAccountName == null) { throw new ArgumentNullException("jobAccountName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Location == null) { throw new ArgumentNullException("parameters.Location"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (parameters.Properties.DatabaseId == null) { throw new ArgumentNullException("parameters.Properties.DatabaseId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("jobAccountName", jobAccountName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/jobAccounts/"; url = url + Uri.EscapeDataString(jobAccountName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject jobAccountCreateOrUpdateParametersValue = new JObject(); requestDoc = jobAccountCreateOrUpdateParametersValue; JObject propertiesValue = new JObject(); jobAccountCreateOrUpdateParametersValue["properties"] = propertiesValue; propertiesValue["databaseId"] = parameters.Properties.DatabaseId; jobAccountCreateOrUpdateParametersValue["location"] = parameters.Location; if (parameters.Tags != null) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } jobAccountCreateOrUpdateParametersValue["tags"] = tagsDictionary; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobAccountOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobAccountOperationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } JobAccount jobAccountInstance = new JobAccount(); result.JobAccount = jobAccountInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { JobAccountProperties propertiesInstance = new JobAccountProperties(); jobAccountInstance.Properties = propertiesInstance; JToken databaseIdValue = propertiesValue2["databaseId"]; if (databaseIdValue != null && databaseIdValue.Type != JTokenType.Null) { string databaseIdInstance = ((string)databaseIdValue); propertiesInstance.DatabaseId = databaseIdInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); jobAccountInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); jobAccountInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); jobAccountInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); jobAccountInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey2 = ((string)property.Name); string tagsValue2 = ((string)property.Value); jobAccountInstance.Tags.Add(tagsKey2, tagsValue2); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Created) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Begins deleting the Azure SQL Job Account with the given name. To /// determine the status of the operation call /// GetJobAccountOperationStatus. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be deleted. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public async Task<JobAccountOperationResponse> BeginDeleteAsync(string resourceGroupName, string serverName, string jobAccountName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (jobAccountName == null) { throw new ArgumentNullException("jobAccountName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("jobAccountName", jobAccountName); TracingAdapter.Enter(invocationId, this, "BeginDeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/jobAccounts/"; url = url + Uri.EscapeDataString(jobAccountName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobAccountOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobAccountOperationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Creates a new Azure SQL Job Account or updates an existing Azure /// SQL Job Account. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Job Database Server that the /// Job Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be created or /// updated. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Job /// Account. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public async Task<JobAccountOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string jobAccountName, JobAccountCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { SqlManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("jobAccountName", jobAccountName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); JobAccountOperationResponse response = await client.JobAccounts.BeginCreateOrUpdateAsync(resourceGroupName, serverName, jobAccountName, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); JobAccountOperationResponse result = await client.JobAccounts.GetJobAccountOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.JobAccounts.GetJobAccountOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Creates a new Azure SQL Job Account or updates an existing Azure /// SQL Job Account. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Job Database Server that the /// Job Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be created or /// updated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public async Task<JobAccountOperationResponse> DeleteAsync(string resourceGroupName, string serverName, string jobAccountName, CancellationToken cancellationToken) { SqlManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("jobAccountName", jobAccountName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); JobAccountOperationResponse response = await client.JobAccounts.BeginDeleteAsync(resourceGroupName, serverName, jobAccountName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); JobAccountOperationResponse result = await client.JobAccounts.GetJobAccountOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.JobAccounts.GetJobAccountOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Returns information about an Azure SQL Job Account. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be retrieved. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a Get Azure Sql Job Account request. /// </returns> public async Task<JobAccountGetResponse> GetAsync(string resourceGroupName, string serverName, string jobAccountName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (jobAccountName == null) { throw new ArgumentNullException("jobAccountName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("jobAccountName", jobAccountName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/jobAccounts/"; url = url + Uri.EscapeDataString(jobAccountName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobAccountGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobAccountGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JobAccount jobAccountInstance = new JobAccount(); result.JobAccount = jobAccountInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JobAccountProperties propertiesInstance = new JobAccountProperties(); jobAccountInstance.Properties = propertiesInstance; JToken databaseIdValue = propertiesValue["databaseId"]; if (databaseIdValue != null && databaseIdValue.Type != JTokenType.Null) { string databaseIdInstance = ((string)databaseIdValue); propertiesInstance.DatabaseId = databaseIdInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); jobAccountInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); jobAccountInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); jobAccountInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); jobAccountInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); jobAccountInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the status of an Azure Sql Job Account create or update /// operation. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public async Task<JobAccountOperationResponse> GetJobAccountOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetJobAccountOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobAccountOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobAccountOperationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } JobAccount jobAccountInstance = new JobAccount(); result.JobAccount = jobAccountInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JobAccountProperties propertiesInstance = new JobAccountProperties(); jobAccountInstance.Properties = propertiesInstance; JToken databaseIdValue = propertiesValue["databaseId"]; if (databaseIdValue != null && databaseIdValue.Type != JTokenType.Null) { string databaseIdInstance = ((string)databaseIdValue); propertiesInstance.DatabaseId = databaseIdInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); jobAccountInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); jobAccountInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); jobAccountInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); jobAccountInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); jobAccountInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.Created) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns information about Azure SQL Job Accounts. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Accounts are hosted in. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a List Azure Sql Job Accounts request. /// </returns> public async Task<JobAccountListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/jobAccounts"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobAccountListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobAccountListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { JobAccount jobAccountInstance = new JobAccount(); result.JobAccounts.Add(jobAccountInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JobAccountProperties propertiesInstance = new JobAccountProperties(); jobAccountInstance.Properties = propertiesInstance; JToken databaseIdValue = propertiesValue["databaseId"]; if (databaseIdValue != null && databaseIdValue.Type != JTokenType.Null) { string databaseIdInstance = ((string)databaseIdValue); propertiesInstance.DatabaseId = databaseIdInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); jobAccountInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); jobAccountInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); jobAccountInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); jobAccountInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); jobAccountInstance.Tags.Add(tagsKey, tagsValue); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Drawing; using System.Drawing.Text; using System.Linq; using System.Xml.Serialization; namespace Palaso.UI.WindowsForms { /// ---------------------------------------------------------------------------------------- /// <summary> /// Encapsulates a font object that can be serialized. /// </summary> /// ---------------------------------------------------------------------------------------- [XmlType("Font")] public class SerializableFont { [XmlAttribute] public string Name ; [XmlAttribute] public float Size = 10; [XmlAttribute] public bool Bold; [XmlAttribute] public bool Italic; /// ------------------------------------------------------------------------------------ public SerializableFont() { } /// ------------------------------------------------------------------------------------ /// <summary> /// Intializes a new Serializable font object from the specified font. /// </summary> /// ------------------------------------------------------------------------------------ public SerializableFont(Font fnt) { Font = fnt; } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets a font object based on the SerializableFont's settings or sets the /// SerializableFont's settings. /// </summary> /// ------------------------------------------------------------------------------------ [XmlIgnore] public Font Font { get { if (Name == null) return null; FontStyle style = FontStyle.Regular; if (Bold) style = FontStyle.Bold; if (Italic) style |= FontStyle.Italic; return FontHelper.MakeFont(Name, (int)Size, style); } set { if (value == null) Name = null; else { Name = value.Name; Size = value.SizeInPoints; Bold = value.Bold; Italic = value.Italic; } } } } /// ---------------------------------------------------------------------------------------- /// <summary> /// Misc. font helper methods. /// </summary> /// ---------------------------------------------------------------------------------------- public static class FontHelper { /// -------------------------------------------------------------------------------- static FontHelper() { ResetFonts(); } /// ------------------------------------------------------------------------------------ public static void ResetFonts() { UIFont = (Font)SystemFonts.MenuFont.Clone(); } /// ------------------------------------------------------------------------------------ /// <summary> /// Determines if the specified font is installed on the computer. /// </summary> /// ------------------------------------------------------------------------------------ public static bool FontInstalled(string fontName) { fontName = fontName.ToLower(); using (var installedFonts = new InstalledFontCollection()) { if (installedFonts.Families.Any(f => f.Name.ToLower() == fontName)) return true; } return false; } /// ------------------------------------------------------------------------------------ /// <summary> /// Creates a new font object that is a regualar style derivative of the specified /// font, having the specified size. /// </summary> /// ------------------------------------------------------------------------------------ public static Font MakeRegularFontDerivative(Font fnt, float size) { return MakeFont((fnt ?? UIFont).FontFamily.Name, size, FontStyle.Regular); } /// ------------------------------------------------------------------------------------ /// <summary> /// Creates a string containing three pieces of information about the specified font: /// the name, size and style. /// </summary> /// ------------------------------------------------------------------------------------ public static string FontToString(Font fnt) { if (fnt == null) return null; return fnt.Name + ", " + fnt.SizeInPoints + ", " + fnt.Style; } /// ------------------------------------------------------------------------------------ /// <summary> /// Creates a font object with the specified properties. If an error occurs while /// making the font (e.g. because the font doesn't support a particular style) a /// fallback scheme is used. /// </summary> /// ------------------------------------------------------------------------------------ public static Font MakeFont(string fontString) { if (fontString == null) return SystemFonts.DefaultFont; var name = SystemFonts.DefaultFont.FontFamily.Name; var size = SystemFonts.DefaultFont.SizeInPoints; var style = FontStyle.Regular; var parts = fontString.Split(','); if (parts.Length > 0) name = parts[0]; if (parts.Length > 1) float.TryParse(parts[1], out size); if (parts.Length > 2) { try { style = (FontStyle)Enum.Parse(typeof(FontStyle), parts[2]); } catch { } } return MakeFont(name, size, style); } /// ------------------------------------------------------------------------------------ /// <summary> /// Creates a font object with the specified properties. If an error occurs while /// making the font (e.g. because the font doesn't support a particular style) a /// fallback scheme is used. /// </summary> /// ------------------------------------------------------------------------------------ public static Font MakeFont(Font fnt, float size, FontStyle style) { return MakeFont(fnt.FontFamily.Name, size, style); } /// ------------------------------------------------------------------------------------ /// <summary> /// Creates a font object with the specified properties. If an error occurs while /// making the font (e.g. because the font doesn't support a particular style) a /// fallback scheme is used. /// </summary> /// ------------------------------------------------------------------------------------ public static Font MakeFont(Font fnt, float size) { return MakeFont(fnt.FontFamily.Name, size, fnt.Style); } /// ------------------------------------------------------------------------------------ /// <summary> /// Creates a font object with the specified properties. If an error occurs while /// making the font (e.g. because the font doesn't support a particular style) a /// fallback scheme is used. /// </summary> /// ------------------------------------------------------------------------------------ public static Font MakeFont(Font fnt, FontStyle style) { return MakeFont(fnt.FontFamily.Name, fnt.SizeInPoints, style); } /// ------------------------------------------------------------------------------------ /// <summary> /// Creates a font object with the specified properties. If an error occurs while /// making the font (e.g. because the font doesn't support a particular style) a /// fallback scheme is used. /// </summary> /// ------------------------------------------------------------------------------------ public static Font MakeFont(string fontName, float size, FontStyle style) { // On Mono there is an 139 exit code if we pass a reference to the FontFamily // to the Font constructor, but not if we pass the FontFamily.Name. try { string familyName = null; bool supportsStyle = false; // on Linux it is possible to get multiple font families with the same name foreach (var family in FontFamily.Families.Where(f => f.Name == fontName)) { // if the font supports the requested style, use it now if (family.IsStyleAvailable(style)) return new Font(family.Name, size, style, GraphicsUnit.Point); // keep looking if the font has the correct name, but does not support the desired style familyName = family.Name; } // if the requested font was not found, use the default font if (string.IsNullOrEmpty(familyName)) { familyName = UIFont.FontFamily.Name; supportsStyle = UIFont.FontFamily.IsStyleAvailable(style); } return supportsStyle ? new Font(familyName, size, style, GraphicsUnit.Point) : new Font(familyName, size, GraphicsUnit.Point); } catch (Exception e) { Console.WriteLine(e); throw; } } /// -------------------------------------------------------------------------------- public static bool GetSupportsRegular(string fontName) { return GetSupportsStyle(fontName, FontStyle.Regular); } /// -------------------------------------------------------------------------------- public static bool GetSupportsBold(string fontName) { return GetSupportsStyle(fontName, FontStyle.Bold); } /// -------------------------------------------------------------------------------- public static bool GetSupportsItalic(string fontName) { return GetSupportsStyle(fontName, FontStyle.Italic); } /// -------------------------------------------------------------------------------- public static bool GetSupportsStyle(string fontName, FontStyle style) { var family = FontFamily.Families.SingleOrDefault(f => f.Name == fontName); return (family != null && family.IsStyleAvailable(style)); } /// -------------------------------------------------------------------------------- /// <summary> /// Compares the font face name, size and style of two fonts. /// </summary> /// -------------------------------------------------------------------------------- public static bool AreFontsSame(Font x, Font y) { if (x == null || y == null) return false; return (x.Name == y.Name && x.Size.Equals(y.Size) && x.Style == y.Style); } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets the desired font for most UI elements. /// </summary> /// ------------------------------------------------------------------------------------ public static Font UIFont { get; set; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Search { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// DataSourcesOperations operations. /// </summary> internal partial class DataSourcesOperations : IServiceOperations<SearchServiceClient>, IDataSourcesOperations { /// <summary> /// Initializes a new instance of the DataSourcesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataSourcesOperations(SearchServiceClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the SearchServiceClient /// </summary> public SearchServiceClient Client { get; private set; } /// <summary> /// Creates a new Azure Search datasource or updates a datasource if it /// already exists. /// <see href="https://docs.microsoft.com/rest/api/searchservice/Update-Data-Source" /> /// </summary> /// <param name='dataSourceName'> /// The name of the datasource to create or update. /// </param> /// <param name='dataSource'> /// The definition of the datasource to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='accessCondition'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<DataSource>> CreateOrUpdateWithHttpMessagesAsync(string dataSourceName, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dataSourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSourceName"); } if (dataSource == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSource"); } if (dataSource != null) { dataSource.Validate(); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } string ifMatch = default(string); if (accessCondition != null) { ifMatch = accessCondition.IfMatch; } string ifNoneMatch = default(string); if (accessCondition != null) { ifNoneMatch = accessCondition.IfNoneMatch; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dataSourceName", dataSourceName); tracingParameters.Add("dataSource", dataSource); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("ifNoneMatch", ifNoneMatch); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources('{dataSourceName}')").ToString(); _url = _url.Replace("{dataSourceName}", Uri.EscapeDataString(dataSourceName)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (ifNoneMatch != null) { if (_httpRequest.Headers.Contains("If-None-Match")) { _httpRequest.Headers.Remove("If-None-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(dataSource != null) { _requestContent = SafeJsonConvert.SerializeObject(dataSource, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DataSource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DataSource>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DataSource>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes an Azure Search datasource. /// <see href="https://docs.microsoft.com/rest/api/searchservice/Delete-Data-Source" /> /// </summary> /// <param name='dataSourceName'> /// The name of the datasource to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='accessCondition'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dataSourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSourceName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } string ifMatch = default(string); if (accessCondition != null) { ifMatch = accessCondition.IfMatch; } string ifNoneMatch = default(string); if (accessCondition != null) { ifNoneMatch = accessCondition.IfNoneMatch; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dataSourceName", dataSourceName); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("ifNoneMatch", ifNoneMatch); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources('{dataSourceName}')").ToString(); _url = _url.Replace("{dataSourceName}", Uri.EscapeDataString(dataSourceName)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (ifNoneMatch != null) { if (_httpRequest.Headers.Contains("If-None-Match")) { _httpRequest.Headers.Remove("If-None-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 404) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieves a datasource definition from Azure Search. /// <see href="https://docs.microsoft.com/rest/api/searchservice/Get-Data-Source" /> /// </summary> /// <param name='dataSourceName'> /// The name of the datasource to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<DataSource>> GetWithHttpMessagesAsync(string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dataSourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSourceName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dataSourceName", dataSourceName); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources('{dataSourceName}')").ToString(); _url = _url.Replace("{dataSourceName}", Uri.EscapeDataString(dataSourceName)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DataSource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DataSource>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all datasources available for an Azure Search service. /// <see href="https://docs.microsoft.com/rest/api/searchservice/List-Data-Sources" /> /// </summary> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<DataSourceListResult>> ListWithHttpMessagesAsync(SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DataSourceListResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DataSourceListResult>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates a new Azure Search datasource. /// <see href="https://docs.microsoft.com/rest/api/searchservice/Create-Data-Source" /> /// </summary> /// <param name='dataSource'> /// The definition of the datasource to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<DataSource>> CreateWithHttpMessagesAsync(DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dataSource == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSource"); } if (dataSource != null) { dataSource.Validate(); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dataSource", dataSource); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(dataSource != null) { _requestContent = SafeJsonConvert.SerializeObject(dataSource, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DataSource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DataSource>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//--------------------------------------------------------------------------- // // <copyright file="PathSegmentCollection.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Effects; using System.Windows.Media.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Windows.Media.Converters; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media { /// <summary> /// A collection of PathSegment objects. /// </summary> public sealed partial class PathSegmentCollection : Animatable, IList, IList<PathSegment> { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new PathSegmentCollection Clone() { return (PathSegmentCollection)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new PathSegmentCollection CloneCurrentValue() { return (PathSegmentCollection)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region IList<T> /// <summary> /// Adds "value" to the list /// </summary> public void Add(PathSegment value) { AddHelper(value); } /// <summary> /// Removes all elements from the list /// </summary> public void Clear() { WritePreamble(); for (int i = _collection.Count - 1; i >= 0; i--) { OnFreezablePropertyChanged(/* oldValue = */ _collection[i], /* newValue = */ null); } _collection.Clear(); Debug.Assert(_collection.Count == 0); ++_version; WritePostscript(); } /// <summary> /// Determines if the list contains "value" /// </summary> public bool Contains(PathSegment value) { ReadPreamble(); return _collection.Contains(value); } /// <summary> /// Returns the index of "value" in the list /// </summary> public int IndexOf(PathSegment value) { ReadPreamble(); return _collection.IndexOf(value); } /// <summary> /// Inserts "value" into the list at the specified position /// </summary> public void Insert(int index, PathSegment value) { if (value == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } WritePreamble(); OnFreezablePropertyChanged(/* oldValue = */ null, /* newValue = */ value); _collection.Insert(index, value); ++_version; WritePostscript(); } /// <summary> /// Removes "value" from the list /// </summary> public bool Remove(PathSegment value) { WritePreamble(); // By design collections "succeed silently" if you attempt to remove an item // not in the collection. Therefore we need to first verify the old value exists // before calling OnFreezablePropertyChanged. Since we already need to locate // the item in the collection we keep the index and use RemoveAt(...) to do // the work. (Windows OS #1016178) // We use the public IndexOf to guard our UIContext since OnFreezablePropertyChanged // is only called conditionally. IList.IndexOf returns -1 if the value is not found. int index = IndexOf(value); if (index >= 0) { PathSegment oldValue = _collection[index]; OnFreezablePropertyChanged(oldValue, null); _collection.RemoveAt(index); ++_version; WritePostscript(); return true; } // Collection_Remove returns true, calls WritePostscript, // increments version, and does UpdateResource if it succeeds return false; } /// <summary> /// Removes the element at the specified index /// </summary> public void RemoveAt(int index) { RemoveAtWithoutFiringPublicEvents(index); // RemoveAtWithoutFiringPublicEvents incremented the version WritePostscript(); } /// <summary> /// Removes the element at the specified index without firing /// the public Changed event. /// The caller - typically a public method - is responsible for calling /// WritePostscript if appropriate. /// </summary> internal void RemoveAtWithoutFiringPublicEvents(int index) { WritePreamble(); PathSegment oldValue = _collection[ index ]; OnFreezablePropertyChanged(oldValue, null); _collection.RemoveAt(index); ++_version; // No WritePostScript to avoid firing the Changed event. } /// <summary> /// Indexer for the collection /// </summary> public PathSegment this[int index] { get { ReadPreamble(); return _collection[index]; } set { if (value == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } WritePreamble(); if (!Object.ReferenceEquals(_collection[ index ], value)) { PathSegment oldValue = _collection[ index ]; OnFreezablePropertyChanged(oldValue, value); _collection[ index ] = value; } ++_version; WritePostscript(); } } #endregion #region ICollection<T> /// <summary> /// The number of elements contained in the collection. /// </summary> public int Count { get { ReadPreamble(); return _collection.Count; } } /// <summary> /// Copies the elements of the collection into "array" starting at "index" /// </summary> public void CopyTo(PathSegment[] array, int index) { ReadPreamble(); if (array == null) { throw new ArgumentNullException("array"); } // This will not throw in the case that we are copying // from an empty collection. This is consistent with the // BCL Collection implementations. (Windows 1587365) if (index < 0 || (index + _collection.Count) > array.Length) { throw new ArgumentOutOfRangeException("index"); } _collection.CopyTo(array, index); } bool ICollection<PathSegment>.IsReadOnly { get { ReadPreamble(); return IsFrozen; } } #endregion #region IEnumerable<T> /// <summary> /// Returns an enumerator for the collection /// </summary> public Enumerator GetEnumerator() { ReadPreamble(); return new Enumerator(this); } IEnumerator<PathSegment> IEnumerable<PathSegment>.GetEnumerator() { return this.GetEnumerator(); } #endregion #region IList bool IList.IsReadOnly { get { return ((ICollection<PathSegment>)this).IsReadOnly; } } bool IList.IsFixedSize { get { ReadPreamble(); return IsFrozen; } } object IList.this[int index] { get { return this[index]; } set { // Forwards to typed implementation this[index] = Cast(value); } } int IList.Add(object value) { // Forward to typed helper return AddHelper(Cast(value)); } bool IList.Contains(object value) { return Contains(value as PathSegment); } int IList.IndexOf(object value) { return IndexOf(value as PathSegment); } void IList.Insert(int index, object value) { // Forward to IList<T> Insert Insert(index, Cast(value)); } void IList.Remove(object value) { Remove(value as PathSegment); } #endregion #region ICollection void ICollection.CopyTo(Array array, int index) { ReadPreamble(); if (array == null) { throw new ArgumentNullException("array"); } // This will not throw in the case that we are copying // from an empty collection. This is consistent with the // BCL Collection implementations. (Windows 1587365) if (index < 0 || (index + _collection.Count) > array.Length) { throw new ArgumentOutOfRangeException("index"); } if (array.Rank != 1) { throw new ArgumentException(SR.Get(SRID.Collection_BadRank)); } // Elsewhere in the collection we throw an AE when the type is // bad so we do it here as well to be consistent try { int count = _collection.Count; for (int i = 0; i < count; i++) { array.SetValue(_collection[i], index + i); } } catch (InvalidCastException e) { throw new ArgumentException(SR.Get(SRID.Collection_BadDestArray, this.GetType().Name), e); } } bool ICollection.IsSynchronized { get { ReadPreamble(); return IsFrozen || Dispatcher != null; } } object ICollection.SyncRoot { get { ReadPreamble(); return this; } } #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Internal Helpers /// <summary> /// A frozen empty PathSegmentCollection. /// </summary> internal static PathSegmentCollection Empty { get { if (s_empty == null) { PathSegmentCollection collection = new PathSegmentCollection(); collection.Freeze(); s_empty = collection; } return s_empty; } } /// <summary> /// Helper to return read only access. /// </summary> internal PathSegment Internal_GetItem(int i) { return _collection[i]; } /// <summary> /// Freezable collections need to notify their contained Freezables /// about the change in the InheritanceContext /// </summary> internal override void OnInheritanceContextChangedCore(EventArgs args) { base.OnInheritanceContextChangedCore(args); for (int i=0; i<this.Count; i++) { DependencyObject inheritanceChild = _collection[i]; if (inheritanceChild!= null && inheritanceChild.InheritanceContext == this) { inheritanceChild.OnInheritanceContextChanged(args); } } } #endregion #region Private Helpers private PathSegment Cast(object value) { if( value == null ) { throw new System.ArgumentNullException("value"); } if (!(value is PathSegment)) { throw new System.ArgumentException(SR.Get(SRID.Collection_BadType, this.GetType().Name, value.GetType().Name, "PathSegment")); } return (PathSegment) value; } // IList.Add returns int and IList<T>.Add does not. This // is called by both Adds and IList<T>'s just ignores the // integer private int AddHelper(PathSegment value) { int index = AddWithoutFiringPublicEvents(value); // AddAtWithoutFiringPublicEvents incremented the version WritePostscript(); return index; } internal int AddWithoutFiringPublicEvents(PathSegment value) { int index = -1; if (value == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } WritePreamble(); PathSegment newValue = value; OnFreezablePropertyChanged(/* oldValue = */ null, newValue); index = _collection.Add(newValue); ++_version; // No WritePostScript to avoid firing the Changed event. return index; } #endregion Private Helpers private static PathSegmentCollection s_empty; #region Public Properties #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new PathSegmentCollection(); } /// <summary> /// Implementation of Freezable.CloneCore() /// </summary> protected override void CloneCore(Freezable source) { PathSegmentCollection sourcePathSegmentCollection = (PathSegmentCollection) source; base.CloneCore(source); int count = sourcePathSegmentCollection._collection.Count; _collection = new FrugalStructList<PathSegment>(count); for (int i = 0; i < count; i++) { PathSegment newValue = (PathSegment) sourcePathSegmentCollection._collection[i].Clone(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); } } /// <summary> /// Implementation of Freezable.CloneCurrentValueCore() /// </summary> protected override void CloneCurrentValueCore(Freezable source) { PathSegmentCollection sourcePathSegmentCollection = (PathSegmentCollection) source; base.CloneCurrentValueCore(source); int count = sourcePathSegmentCollection._collection.Count; _collection = new FrugalStructList<PathSegment>(count); for (int i = 0; i < count; i++) { PathSegment newValue = (PathSegment) sourcePathSegmentCollection._collection[i].CloneCurrentValue(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); } } /// <summary> /// Implementation of Freezable.GetAsFrozenCore() /// </summary> protected override void GetAsFrozenCore(Freezable source) { PathSegmentCollection sourcePathSegmentCollection = (PathSegmentCollection) source; base.GetAsFrozenCore(source); int count = sourcePathSegmentCollection._collection.Count; _collection = new FrugalStructList<PathSegment>(count); for (int i = 0; i < count; i++) { PathSegment newValue = (PathSegment) sourcePathSegmentCollection._collection[i].GetAsFrozen(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); } } /// <summary> /// Implementation of Freezable.GetCurrentValueAsFrozenCore() /// </summary> protected override void GetCurrentValueAsFrozenCore(Freezable source) { PathSegmentCollection sourcePathSegmentCollection = (PathSegmentCollection) source; base.GetCurrentValueAsFrozenCore(source); int count = sourcePathSegmentCollection._collection.Count; _collection = new FrugalStructList<PathSegment>(count); for (int i = 0; i < count; i++) { PathSegment newValue = (PathSegment) sourcePathSegmentCollection._collection[i].GetCurrentValueAsFrozen(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>. /// </summary> protected override bool FreezeCore(bool isChecking) { bool canFreeze = base.FreezeCore(isChecking); int count = _collection.Count; for (int i = 0; i < count && canFreeze; i++) { canFreeze &= Freezable.Freeze(_collection[i], isChecking); } return canFreeze; } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal FrugalStructList<PathSegment> _collection; internal uint _version = 0; #endregion Internal Fields #region Enumerator /// <summary> /// Enumerates the items in a PathSegmentCollection /// </summary> public struct Enumerator : IEnumerator, IEnumerator<PathSegment> { #region Constructor internal Enumerator(PathSegmentCollection list) { Debug.Assert(list != null, "list may not be null."); _list = list; _version = list._version; _index = -1; _current = default(PathSegment); } #endregion #region Methods void IDisposable.Dispose() { } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// true if the enumerator was successfully advanced to the next element, /// false if the enumerator has passed the end of the collection. /// </returns> public bool MoveNext() { _list.ReadPreamble(); if (_version == _list._version) { if (_index > -2 && _index < _list._collection.Count - 1) { _current = _list._collection[++_index]; return true; } else { _index = -2; // -2 indicates "past the end" return false; } } else { throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged)); } } /// <summary> /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// </summary> public void Reset() { _list.ReadPreamble(); if (_version == _list._version) { _index = -1; } else { throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged)); } } #endregion #region Properties object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Current element /// /// The behavior of IEnumerable&lt;T>.Current is undefined /// before the first MoveNext and after we have walked /// off the end of the list. However, the IEnumerable.Current /// contract requires that we throw exceptions /// </summary> public PathSegment Current { get { if (_index > -1) { return _current; } else if (_index == -1) { throw new InvalidOperationException(SR.Get(SRID.Enumerator_NotStarted)); } else { Debug.Assert(_index == -2, "expected -2, got " + _index + "\n"); throw new InvalidOperationException(SR.Get(SRID.Enumerator_ReachedEnd)); } } } #endregion #region Data private PathSegment _current; private PathSegmentCollection _list; private uint _version; private int _index; #endregion } #endregion #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ /// <summary> /// Initializes a new instance that is empty. /// </summary> public PathSegmentCollection() { _collection = new FrugalStructList<PathSegment>(); } /// <summary> /// Initializes a new instance that is empty and has the specified initial capacity. /// </summary> /// <param name="capacity"> int - The number of elements that the new list is initially capable of storing. </param> public PathSegmentCollection(int capacity) { _collection = new FrugalStructList<PathSegment>(capacity); } /// <summary> /// Creates a PathSegmentCollection with all of the same elements as collection /// </summary> public PathSegmentCollection(IEnumerable<PathSegment> collection) { // The WritePreamble and WritePostscript aren't technically necessary // in the constructor as of 1/20/05 but they are put here in case // their behavior changes at a later date WritePreamble(); if (collection != null) { bool needsItemValidation = true; ICollection<PathSegment> icollectionOfT = collection as ICollection<PathSegment>; if (icollectionOfT != null) { _collection = new FrugalStructList<PathSegment>(icollectionOfT); } else { ICollection icollection = collection as ICollection; if (icollection != null) // an IC but not and IC<T> { _collection = new FrugalStructList<PathSegment>(icollection); } else // not a IC or IC<T> so fall back to the slower Add { _collection = new FrugalStructList<PathSegment>(); foreach (PathSegment item in collection) { if (item == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } PathSegment newValue = item; OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); } needsItemValidation = false; } } if (needsItemValidation) { foreach (PathSegment item in collection) { if (item == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } OnFreezablePropertyChanged(/* oldValue = */ null, item); } } WritePostscript(); } else { throw new ArgumentNullException("collection"); } } #endregion Constructors } }
using System; using System.Collections.Generic; using System.Text; using Inbox2.Framework.Interop.iFilters; using Microsoft.Win32; using System.IO; using System.Runtime.InteropServices.ComTypes; using System.Runtime.InteropServices; namespace Inbox2.Framework.Interop.iFilters { /// <summary> /// FilterLoader finds the dll and ClassID of the COM object responsible /// for filtering a specific file extension. /// It then loads that dll, creates the appropriate COM object and returns /// a pointer to an IFilter instance /// </summary> static class FilterLoader { #region CacheEntry private class CacheEntry { public string DllName; public string ClassName; public CacheEntry(string dllName, string className) { DllName=dllName; ClassName=className; } } #endregion static Dictionary<string, CacheEntry> _cache=new Dictionary<string, CacheEntry>(); #region Registry Read String helper static string ReadStrFromHKLM(string key) { return ReadStrFromHKLM(key,null); } static string ReadStrFromHKLM(string key, string value) { RegistryKey rk=Registry.LocalMachine.OpenSubKey(key); if (rk==null) return null; using (rk) { return (string)rk.GetValue(value); } } #endregion /// <summary> /// finds an IFilter implementation for a file type /// </summary> /// <param name="ext">The extension of the file</param> /// <returns>an IFilter instance used to retreive text from that file type</returns> private static IFilter LoadIFilter(string ext) { string dllName, filterPersistClass; //Find the dll and ClassID if (GetFilterDllAndClass(ext, out dllName, out filterPersistClass)) { //load the dll and return an IFilter instance. return LoadFilterFromDll(dllName, filterPersistClass); } return null; } internal static IFilter LoadAndInitIFilter(string fileName) { return LoadAndInitIFilter(fileName,Path.GetExtension(fileName)); } internal static IFilter LoadAndInitIFilter(string fileName, string extension) { IFilter filter=LoadIFilter(extension); if (filter==null) return null; IPersistFile persistFile=(filter as IPersistFile); if (persistFile!=null) { persistFile.Load(fileName, 0); IFILTER_FLAGS flags; IFILTER_INIT iflags = IFILTER_INIT.CANON_HYPHENS | IFILTER_INIT.CANON_PARAGRAPHS | IFILTER_INIT.CANON_SPACES | IFILTER_INIT.APPLY_INDEX_ATTRIBUTES | IFILTER_INIT.HARD_LINE_BREAKS | IFILTER_INIT.FILTER_OWNED_VALUE_OK; if (filter.Init(iflags, 0, IntPtr.Zero, out flags)==IFilterReturnCode.S_OK) return filter; } //If we failed to retreive an IPersistFile interface or to initialize //the filter, we release it and return null. Marshal.ReleaseComObject(filter); return null; } private static IFilter LoadFilterFromDll(string dllName, string filterPersistClass) { //Get a classFactory for our classID IClassFactory classFactory=ComHelper.GetClassFactory(dllName, filterPersistClass); if (classFactory==null) return null; //And create an IFilter instance using that class factory Guid IFilterGUID=new Guid("89BCB740-6119-101A-BCB7-00DD010655AF"); Object obj; classFactory.CreateInstance(null, ref IFilterGUID, out obj); return (obj as IFilter); } private static bool GetFilterDllAndClass(string ext, out string dllName, out string filterPersistClass) { if (!GetFilterDllAndClassFromCache(ext, out dllName, out filterPersistClass)) { string persistentHandlerClass; persistentHandlerClass=GetPersistentHandlerClass(ext,true); if (persistentHandlerClass!=null) { GetFilterDllAndClassFromPersistentHandler(persistentHandlerClass, out dllName, out filterPersistClass); } AddExtensionToCache(ext, dllName, filterPersistClass); } return (dllName!=null && filterPersistClass!=null); } private static void AddExtensionToCache(string ext, string dllName, string filterPersistClass) { lock (_cache) { if (!_cache.ContainsKey(ext.ToLower())) _cache.Add(ext.ToLower(), new CacheEntry(dllName, filterPersistClass)); } } private static bool GetFilterDllAndClassFromPersistentHandler(string persistentHandlerClass, out string dllName, out string filterPersistClass) { dllName=null; filterPersistClass=null; //Read the CLASS ID of the IFilter persistent handler filterPersistClass=ReadStrFromHKLM(@"Software\Classes\CLSID\" + persistentHandlerClass + @"\PersistentAddinsRegistered\{89BCB740-6119-101A-BCB7-00DD010655AF}"); if (String.IsNullOrEmpty(filterPersistClass)) return false; //Read the dll name dllName=ReadStrFromHKLM(@"Software\Classes\CLSID\" + filterPersistClass + @"\InprocServer32"); return (!String.IsNullOrEmpty(dllName)); } private static string GetPersistentHandlerClass(string ext, bool searchContentType) { //Try getting the info from the file extension string persistentHandlerClass=GetPersistentHandlerClassFromExtension(ext); if (String.IsNullOrEmpty(persistentHandlerClass)) //try getting the info from the document type persistentHandlerClass=GetPersistentHandlerClassFromDocumentType(ext); if (searchContentType && String.IsNullOrEmpty(persistentHandlerClass)) //Try getting the info from the Content Type persistentHandlerClass=GetPersistentHandlerClassFromContentType(ext); return persistentHandlerClass; } private static string GetPersistentHandlerClassFromContentType(string ext) { string contentType=ReadStrFromHKLM(@"Software\Classes\"+ext,"Content Type"); if (String.IsNullOrEmpty(contentType)) return null; string contentTypeExtension=ReadStrFromHKLM(@"Software\Classes\MIME\Database\Content Type\"+contentType, "Extension"); if (ext.Equals(contentTypeExtension, StringComparison.CurrentCultureIgnoreCase)) return null; //No need to look further. This extension does not have any persistent handler //We know the extension that is assciated with that content type. Simply try again with the new extension return GetPersistentHandlerClass(contentTypeExtension, false); //Don't search content type this time. } private static string GetPersistentHandlerClassFromDocumentType(string ext) { //Get the DocumentType of this file extension string docType=ReadStrFromHKLM(@"Software\Classes\"+ext); if (String.IsNullOrEmpty(docType)) return null; //Get the Class ID for this document type string docClass=ReadStrFromHKLM(@"Software\Classes\" + docType + @"\CLSID"); if (String.IsNullOrEmpty(docType)) return null; //Now get the PersistentHandler for that Class ID return ReadStrFromHKLM(@"Software\Classes\CLSID\" + docClass + @"\PersistentHandler"); } private static string GetPersistentHandlerClassFromExtension(string ext) { return ReadStrFromHKLM(@"Software\Classes\"+ext+@"\PersistentHandler"); } private static bool GetFilterDllAndClassFromCache(string ext, out string dllName, out string filterPersistClass) { string lowerExt=ext.ToLower(); lock (_cache) { CacheEntry cacheEntry; if (_cache.TryGetValue(lowerExt, out cacheEntry)) { dllName=cacheEntry.DllName; filterPersistClass=cacheEntry.ClassName; return true; } } dllName=null; filterPersistClass=null; return false; } } }
// 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.Web; using WebsitePanel.EnterpriseServer; namespace WebsitePanel.Portal { public partial class HostingAddonsEditAddon : WebsitePanelModuleBase { protected bool ShouldCopyCurrentHostingAddon() { return (HttpContext.Current.Request["TargetAction"] == "Copy"); } protected void Page_Load(object sender, EventArgs e) { btnDelete.Visible = (PanelRequest.PlanID > 0) && (!ShouldCopyCurrentHostingAddon()); if (!IsPostBack) { try { BindPlan(); } catch (Exception ex) { ShowErrorMessage("ADDON_GET_ADDON", ex); return; } } } private void BindPlan() { if (PanelRequest.PlanID == 0) { // new plan BindQuotas(); return; } HostingPlanInfo plan = ES.Services.Packages.GetHostingPlan(PanelRequest.PlanID); if (plan == null) // plan not found RedirectBack(); if (ShouldCopyCurrentHostingAddon()) { plan.PlanId = 0; plan.PlanName = "Copy of " + plan.PlanName; } // bind plan txtPlanName.Text = PortalAntiXSS.DecodeOld(plan.PlanName); txtPlanDescription.Text = PortalAntiXSS.DecodeOld(plan.PlanDescription); //chkAvailable.Checked = plan.Available; //txtSetupPrice.Text = plan.SetupPrice.ToString("0.00"); //txtRecurringPrice.Text = plan.RecurringPrice.ToString("0.00"); //txtRecurrenceLength.Text = plan.RecurrenceLength.ToString(); //Utils.SelectListItem(ddlRecurrenceUnit, plan.RecurrenceUnit); // bind quotas BindQuotas(); } private void BindQuotas() { hostingPlansQuotas.BindPlanQuotas(-1, PanelRequest.PlanID, -1); } private void SavePlan() { if (!Page.IsValid) return; // gather form info HostingPlanInfo plan = new HostingPlanInfo(); plan.UserId = PanelSecurity.SelectedUserId; plan.PlanId = PanelRequest.PlanID; plan.IsAddon = true; plan.PlanName = txtPlanName.Text; plan.PlanDescription = txtPlanDescription.Text; plan.Available = true; // always available plan.SetupPrice = 0; plan.RecurringPrice = 0; plan.RecurrenceLength = 1; plan.RecurrenceUnit = 2; // month plan.Groups = hostingPlansQuotas.Groups; plan.Quotas = hostingPlansQuotas.Quotas; int planId = PanelRequest.PlanID; if ((PanelRequest.PlanID == 0) || ShouldCopyCurrentHostingAddon()) { // new plan try { planId = ES.Services.Packages.AddHostingPlan(plan); if (planId < 0) { ShowResultMessage(planId); return; } } catch (Exception ex) { ShowErrorMessage("ADDON_ADD_ADDON", ex); return; } } else { // update plan try { PackageResult result = ES.Services.Packages.UpdateHostingPlan(plan); lblMessage.Text = PortalAntiXSS.Encode(GetExceedingQuotasMessage(result.ExceedingQuotas)); if (result.Result < 0) { ShowResultMessage(result.Result); return; } } catch (Exception ex) { ShowErrorMessage("ADDON_UPDATE_ADDON", ex); return; } } // redirect RedirectBack(); } private void DeletePlan() { try { int result = ES.Services.Packages.DeleteHostingPlan(PanelRequest.PlanID); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("ADDON_DELETE_ADDON", ex); return; } // redirect RedirectBack(); } protected void btnSave_Click(object sender, EventArgs e) { SavePlan(); } protected void btnCancel_Click(object sender, EventArgs e) { RedirectBack(); } protected void btnDelete_Click(object sender, EventArgs e) { DeletePlan(); } private void RedirectBack() { Response.Redirect(NavigateURL(PortalUtils.USER_ID_PARAM, PanelSecurity.SelectedUserId.ToString())); } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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.Text; using Axiom.Media; using Axiom.Core; using System.Diagnostics; using Axiom.MathLib; namespace Axiom.SceneManagers.Multiverse { public class Roads : IDisposable { List<Road> roads; SparsePageMask mask; public Roads() { roads = new List<Road>(); mask = new SparsePageMask(TerrainManager.Instance.PageSize); TerrainManager.Instance.PageVisibility += new PageVisibilityEventHandler(PageVisibilityHandler); } public Road CreateRoad(String name) { Road road = new Road(name, this); roads.Add(road); return road; } public void RemoveRoad(Road road) { roads.Remove(road); road.Dispose(); RebuildMask(); } private void PageVisibilityHandler(object sender, PageVisibilityEventArgs msg) { TerrainPage terrainPage = sender as TerrainPage; if (msg.visible) { // the page has become visible, so generate and assign the hilight mask texture Debug.Assert(terrainPage.HilightMask == null); SetRoadMask(terrainPage); } else { // the page is moving out of the visible area, so free up the mask textures if ( terrainPage.HilightMask != null ) { Texture hilightMask = terrainPage.HilightMask; terrainPage.HilightType = TerrainPage.PageHilightType.None; terrainPage.HilightMask = null; TextureManager.Instance.Unload(hilightMask); } } } private void SetRoadMask(TerrainPage terrainPage) { // generate a texture from the mask PageCoord pc = new PageCoord(terrainPage.Location, TerrainManager.Instance.PageSize); byte[] byteMask = mask.GetMask(pc); if (byteMask != null) { Image maskImage = Image.FromDynamicImage(byteMask, mask.PageSize, mask.PageSize, PixelFormat.A8); String texName = String.Format("RoadMask-{0}", pc.ToString()); Texture texImage = TextureManager.Instance.LoadImage(texName, maskImage); terrainPage.HilightMask = texImage; terrainPage.HilightType = TerrainPage.PageHilightType.EdgeSharpBlend; } } private void UpdateRoadMaskTextures() { int numPages = TerrainManager.Instance.PageArraySize; for (int x = 0; x < numPages; x++) { for (int z = 0; z < numPages; z++) { TerrainPage terrainPage = TerrainManager.Instance.LookupPage(x, z).TerrainPage; if ( (terrainPage.HilightMask != null) && (terrainPage.HilightType == TerrainPage.PageHilightType.EdgeSharpBlend) ) { terrainPage.HilightType = TerrainPage.PageHilightType.None; terrainPage.HilightMask.Dispose(); terrainPage.HilightMask = null; } SetRoadMask(terrainPage); } } } //private void SetPageHilights() //{ // PageCoord minVis = TerrainManager.Instance.MinVisiblePage; // PageCoord maxVis = TerrainManager.Instance.MaxVisiblePage; // mask.IterateMasks(new SparsePageMask.ReturnMask(SetRoadMask), minVis, maxVis); //} // when one of the roads changes, we have to rebuild the mask public void RebuildMask() { mask.Clear(); foreach (Road r in roads) { r.RenderMask(); } // XXX - reset hilight masks on all pages when roads change UpdateRoadMaskTextures(); } public SparsePageMask Mask { get { return mask; } } // check if 2 segments intersect private static bool IntersectSegments(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4) { float den = ((p4.y - p3.y) * (p2.x - p1.x)) - ((p4.x - p3.x) * (p2.y - p1.y)); float t1num = ((p4.x - p3.x) * (p1.y - p3.y)) - ((p4.y - p3.y) * (p1.x - p3.x)); float t2num = ((p2.x - p1.x) * (p1.y - p3.y)) - ((p2.y - p1.y) * (p1.x - p3.x)); if (den == 0) { return false; } float t1 = t1num / den; float t2 = t2num / den; // note that we include the endpoint of the second line in the intersection // test, but not the endpoint of the first line. if ((t1 >= 0) && (t1 < 1) && (t2 >= 0) && (t2 <= 1)) { return true; } return false; } private static bool PointInsideBlock(Vector2 blockCornerMin, Vector2 blockCornerMax, Vector2 pt) { return ((pt.x >= blockCornerMin.x) && (pt.x <= blockCornerMax.x) && (pt.y >= blockCornerMin.y) && (pt.y <= blockCornerMax.y)); } private static bool IntersectBlockSegment(Vector2 blockCornerMin, Vector2 blockCornerMax, Vector2 p1, Vector2 p2) { if (PointInsideBlock(blockCornerMin, blockCornerMax, p1) || PointInsideBlock(blockCornerMin, blockCornerMax, p2)) { // if either point is inside the block, then we have an intersection return true; } // XXX - add quick reject here Vector2 c1 = new Vector2(blockCornerMin.x, blockCornerMax.y); Vector2 c2 = new Vector2(blockCornerMax.x, blockCornerMin.y); if (IntersectSegments(p1, p2, blockCornerMin, c1) || IntersectSegments(p1, p2, blockCornerMin, c2) || IntersectSegments(p1, p2, blockCornerMax, c1) || IntersectSegments(p1, p2, blockCornerMax, c2)) { return true; } return false; } public List<Vector2> IntersectBlock(Vector2 blockCornerMin, Vector2 blockCornerMax) { List<Vector2> retSegments = new List<Vector2>(); foreach (Road r in roads) { List<Vector2> roadPts = r.Points; for (int i = 0; i < roadPts.Count - 1; i++) { if (IntersectBlockSegment(blockCornerMin, blockCornerMax, roadPts[i], roadPts[i + 1])) { retSegments.Add(roadPts[i]); retSegments.Add(roadPts[i + 1]); } } } return retSegments; } #region IDisposable Members public void Dispose() { TerrainManager.Instance.PageVisibility -= new PageVisibilityEventHandler(PageVisibilityHandler); // dispose any roads still in collection foreach (Road r in roads) { r.Dispose(); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Globalization; using System.Collections; using System.Text; using System.Reflection; using System.Security; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using Microsoft.Win32; using System.Collections.Generic; using System.Runtime.Versioning; using System.Diagnostics; using Internal.Resources; namespace System.Resources { public partial class ResourceManager { private WindowsRuntimeResourceManagerBase? _WinRTResourceManager; private PRIExceptionInfo? _PRIExceptionInfo; private bool _PRIInitialized; private bool _useUapResourceManagement; private string? GetStringFromPRI(string stringName, CultureInfo? culture, string? neutralResourcesCulture) { Debug.Assert(_useUapResourceManagement); Debug.Assert(_WinRTResourceManager != null); Debug.Assert(_PRIInitialized); // If the caller explicitly passed in a culture that was obtained by calling CultureInfo.CurrentUICulture, // null it out, so that we re-compute it. If we use modern resource lookup, we may end up getting a "better" // match, since CultureInfo objects can't represent all the different languages the Uap resource model supports. if (object.ReferenceEquals(culture, CultureInfo.CurrentUICulture)) { culture = null; } string? startingCulture = culture?.Name; if (_PRIInitialized == false) { // Always throw if we did not fully succeed in initializing the WinRT Resource Manager. if (_PRIExceptionInfo != null && _PRIExceptionInfo.PackageSimpleName != null && _PRIExceptionInfo.ResWFile != null) throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_ResWFileNotLoaded, _PRIExceptionInfo.ResWFile, _PRIExceptionInfo.PackageSimpleName)); throw new MissingManifestResourceException(SR.MissingManifestResource_NoPRIresources); } if (stringName.Length == 0) return null; // Do not handle exceptions. See the comment in SetUapConfiguration about throwing // exception types that the ResourceManager class is not documented to throw. return _WinRTResourceManager.GetString( stringName, string.IsNullOrEmpty(startingCulture) ? null : startingCulture, string.IsNullOrEmpty(neutralResourcesCulture) ? null : neutralResourcesCulture); } // Since we can't directly reference System.Runtime.WindowsRuntime from System.Private.CoreLib, we have to get the type via reflection. // It would be better if we could just implement WindowsRuntimeResourceManager in System.Private.CoreLib, but we can't, because // we can do very little with WinRT in System.Private.CoreLib. internal static WindowsRuntimeResourceManagerBase GetWinRTResourceManager() { #if FEATURE_APPX Type WinRTResourceManagerType = Type.GetType("System.Resources.WindowsRuntimeResourceManager, System.Runtime.WindowsRuntime", throwOnError: true)!; #else // ENABLE_WINRT Assembly hiddenScopeAssembly = Assembly.Load(Internal.Runtime.Augments.RuntimeAugments.HiddenScopeAssemblyName); Type WinRTResourceManagerType = hiddenScopeAssembly.GetType("System.Resources.WindowsRuntimeResourceManager", true); #endif return (WindowsRuntimeResourceManagerBase)Activator.CreateInstance(WinRTResourceManagerType, nonPublic: true)!; } // CoreCLR: When running under AppX, the following rules apply for resource lookup: // // 1) For Framework assemblies, we always use satellite assembly based lookup. // 2) For non-FX assemblies: // // a) If the assembly lives under PLATFORM_RESOURCE_ROOTS (as specified by the host during AppDomain creation), // then we will use satellite assembly based lookup in assemblies like *.resources.dll. // // b) For any other non-FX assembly, we will use the modern resource manager with the premise that app package // contains the PRI resources. // // .NET Native: If it is framework assembly we'll return true. The reason is in .NetNative we don't merge the // resources to the app PRI file. // The framework assemblies are tagged with attribute [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] private static bool ShouldUseUapResourceManagement(Assembly resourcesAssembly) { if (resourcesAssembly == typeof(object).Assembly) // We are not loading resources for System.Private.CoreLib return false; #if FEATURE_APPX // Check to see if the assembly is under PLATFORM_RESOURCE_ROOTS. If it is, then we should use satellite assembly lookup for it. string? platformResourceRoots = (string?)AppContext.GetData("PLATFORM_RESOURCE_ROOTS"); if ((platformResourceRoots != null) && (platformResourceRoots != string.Empty)) { string resourceAssemblyPath = resourcesAssembly.Location; // Loop through the PLATFORM_RESOURCE_ROOTS and see if the assembly is contained in it. foreach (string pathPlatformResourceRoot in platformResourceRoots.Split(Path.PathSeparator)) { if (resourceAssemblyPath.StartsWith(pathPlatformResourceRoot, StringComparison.CurrentCultureIgnoreCase)) { // Found the resource assembly to be present in one of the PLATFORM_RESOURCE_ROOT, so stop the enumeration loop. return false; } } } #else // ENABLE_WINRT foreach (var attrib in resourcesAssembly.GetCustomAttributes()) { AssemblyMetadataAttribute? meta = attrib as AssemblyMetadataAttribute; if (meta != null && meta.Key.Equals(".NETFrameworkAssembly")) { return false; } } #endif return true; } // Only call SetUapConfiguration from ResourceManager constructors, and nowhere else. // Throws MissingManifestResourceException and WinRT HResults private void SetUapConfiguration() { Debug.Assert(_useUapResourceManagement == false); // Only this function writes to this member Debug.Assert(_WinRTResourceManager == null); // Only this function writes to this member Debug.Assert(_PRIInitialized == false); // Only this function writes to this member Debug.Assert(_PRIExceptionInfo == null); // Only this function writes to this member #if FEATURE_APPX if (!ApplicationModel.IsUap) return; #else // ENABLE_WINRT Internal.Runtime.Augments.WinRTInteropCallbacks callbacks = Internal.Runtime.Augments.WinRTInterop.UnsafeCallbacks; if (!(callbacks != null && callbacks.IsAppxModel())) return; #endif Debug.Assert(MainAssembly != null); if (!ShouldUseUapResourceManagement(MainAssembly)) return; _useUapResourceManagement = true; // If we have the type information from the ResourceManager(Type) constructor, we use it. Otherwise, we use BaseNameField. string? reswFilename = _locationInfo == null ? BaseNameField : _locationInfo.FullName; // The only way this can happen is if a class inherited from ResourceManager and // did not set the BaseNameField before calling the protected ResourceManager() constructor. // For other constructors, we would already have thrown an ArgumentNullException by now. // Throwing an ArgumentNullException now is not the right thing to do because technically // ResourceManager() takes no arguments, and because it is not documented as throwing // any exceptions. Instead, let's go through the rest of the initialization with this set to // an empty string. We may in fact fail earlier for another reason, but otherwise we will // throw a MissingManifestResourceException when GetString is called indicating that a // resW filename called "" could not be found. if (reswFilename == null) reswFilename = string.Empty; // At this point it is important NOT to set _useUapResourceManagement to false // if the PRI file does not exist because we are now certain we need to load PRI // resources. We want to fail by throwing a MissingManifestResourceException // if WindowsRuntimeResourceManager.Initialize fails to locate the PRI file. We do not // want to fall back to using satellite assemblies anymore. Note that we would not throw // the MissingManifestResourceException from this function, but from GetString. See the // comment below on the reason for this. _WinRTResourceManager = GetWinRTResourceManager(); try { _PRIInitialized = _WinRTResourceManager.Initialize(MainAssembly.Location, reswFilename, out _PRIExceptionInfo); // Note that _PRIExceptionInfo might be null - this is OK. // In that case we will just throw the generic // MissingManifestResource_NoPRIresources exception. // See the implementation of GetString for more details. } // We would like to be able to throw a MissingManifestResourceException here if PRI resources // could not be loaded for a recognized reason. However, the ResourceManager constructors // that call SetUapConfiguration are not documented as throwing MissingManifestResourceException, // and since they are part of the portable profile, we cannot start throwing a new exception type // as that would break existing portable libraries. Hence we must save the exception information // now and throw the exception on the first call to GetString. catch (FileNotFoundException) { // We will throw MissingManifestResource_NoPRIresources from GetString // when we see that _PRIInitialized is false. } catch (Exception e) { // ERROR_MRM_MAP_NOT_FOUND can be thrown by the call to ResourceManager.get_AllResourceMaps // in WindowsRuntimeResourceManager.Initialize. // In this case _PRIExceptionInfo is now null and we will just throw the generic // MissingManifestResource_NoPRIresources exception. // See the implementation of GetString for more details. if (e.HResult != HResults.ERROR_MRM_MAP_NOT_FOUND) throw; // Unexpected exception code. Bubble it up to the caller. } if (!_PRIInitialized) { _useUapResourceManagement = false; } // Allow all other exception types to bubble up to the caller. // Yes, this causes us to potentially throw exception types that are not documented. // Ultimately the tradeoff is the following: // -We could ignore unknown exceptions or rethrow them as inner exceptions // of exceptions that the ResourceManager class is already documented as throwing. // This would allow existing portable libraries to gracefully recover if they don't care // too much about the ResourceManager object they are using. However it could // mask potentially fatal errors that we are not aware of, such as a disk drive failing. // The alternative, which we chose, is to throw unknown exceptions. This may tear // down the process if the portable library and app don't expect this exception type. // On the other hand, this won't mask potentially fatal errors we don't know about. } } }
#region Using Directives using System; using System.IO; using System.Text; using System.Windows.Forms; using EnvDTE; using Microsoft.Practices.ComponentModel; using Microsoft.Practices.RecipeFramework; #endregion namespace SPALM.SPSF.Library.Actions { /// <summary> /// Exports a given /// </summary> [ServiceDependency(typeof(DTE))] public class WebServiceGenerateWSDL : ConfigurableAction { private ProjectItem _WebServiceFile = null; [Input(Required = true)] public ProjectItem WebServiceFile { get { return _WebServiceFile; } set { _WebServiceFile = value; } } public override void Execute() { DTE service = (DTE)this.GetService(typeof(DTE)); Helpers.ShowProgress(service, "Generating WSDL...", 10); string defaultIISAPP = Helpers.GetDefaultIISWebApp(); string workingDirectory = Path.Combine(Path.GetTempPath(), "SPALMWSDL" + Guid.NewGuid().ToString()); Directory.CreateDirectory(workingDirectory); ProjectItem asmxfileParentFolder = (ProjectItem)WebServiceFile.ProjectItems.Parent; //build if necessary Helpers.WriteToOutputWindow(service, "Compile to get actual version of dll"); Project project = WebServiceFile.ContainingProject; service.Solution.SolutionBuild.BuildProject(service.Solution.SolutionBuild.ActiveConfiguration.Name, project.UniqueName, true); //get the asmx file and copy to /_layouts string projectpath = Helpers.GetFullPathOfProjectItem(project); string projectfolder = Path.GetDirectoryName(projectpath); bool ASMXFileExisted = false; string fullasmxtarget = ""; string asmxfilename = WebServiceFile.Name; string asmxfilenamewithoutext = asmxfilename.Substring(0, asmxfilename.LastIndexOf(".")); string asmxfullPath = Helpers.GetFullPathOfProjectItem(WebServiceFile); if (File.Exists(asmxfullPath)) { string targetfolder = Helpers.GetSharePointHive() + @"\TEMPLATE\LAYOUTS"; Helpers.WriteToOutputWindow(service, "Copying asmx file to _layouts folder"); fullasmxtarget = Path.Combine(targetfolder, asmxfilename); if (File.Exists(fullasmxtarget)) { ASMXFileExisted = true; } File.Copy(asmxfullPath, fullasmxtarget, true); } //add the assembly to the gac string OutputFileName = project.Properties.Item("OutputFileName").Value.ToString(); string OutputPath = project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString(); string assemblypath = Path.Combine(Path.Combine(projectfolder, OutputPath), OutputFileName); if (!File.Exists(assemblypath)) { //check GAC folder of project assemblypath = Path.Combine(projectfolder, "GAC"); if (Directory.Exists(assemblypath)) { assemblypath = Path.Combine(assemblypath, OutputFileName); } } if (!File.Exists(assemblypath)) { string message = "Warning: No assembly in project found"; Helpers.LogMessage(service, this, message); MessageBox.Show(message); } if (File.Exists(assemblypath)) { string gacutilpath = Helpers.GetGACUtil(service); //sear if (File.Exists(gacutilpath)) { Helpers.ShowProgress(service, "Generating WSDL...", 30); Helpers.WriteToOutputWindow(service, "Install dll in GAC", false); Helpers.RunProcess(service, gacutilpath, "/if " + assemblypath, true, workingDirectory, false); Helpers.WriteToOutputWindow(service, "IISReset to force reload of dll", false); Helpers.ShowProgress(service, "Generating WSDL...", 60); Helpers.LogMessage(service, this, "IISRESET..."); Helpers.RunProcess(service, "iisreset", "", true, workingDirectory, false); } else { string message = "GACUTIL.exe not found on your system.\nPlease install .net or Windows SDK.\ni.e. Windows SDK 7.1 http://www.microsoft.com/download/en/details.aspx?id=8442"; Helpers.LogMessage(service, this, message); MessageBox.Show(message); } } //call disco.exe Helpers.LogMessage(service, this, "Getting path to disco.exe..."); string discopath = Helpers.GetDiscoPath(); if (discopath != "") { if (!defaultIISAPP.StartsWith("http:")) { defaultIISAPP = "http://" + defaultIISAPP; } Helpers.ShowProgress(service, "Generating WSDL...", 80); string discoargument = " " + defaultIISAPP + "/_layouts" + Helpers.GetVersionedFolder(service) + "/" + asmxfilename; Helpers.LogMessage(service, this, "Ping server..."); DeploymentHelpers.PingServer(service, discoargument, 20000); Helpers.LogMessage(service, this, "Running disco.exe..."); Helpers.RunProcess(service, discopath, discoargument, true, workingDirectory, false); } else { string message = "Disco.exe not found on your system.\nPlease install .net or Windows SDK.\ni.e. Windows SDK 7.1 http://www.microsoft.com/download/en/details.aspx?id=8442"; Helpers.LogMessage(service, this, message); MessageBox.Show(message); } //adding results to the project //WebService1.disco string finalwsdlpath = ""; string finaldiscopath = ""; string[] wsdls = Directory.GetFiles(workingDirectory, "*.wsdl"); if (wsdls.Length > 0) { finalwsdlpath = wsdls[0]; } string[] discos = Directory.GetFiles(workingDirectory, "*.disco"); if (discos.Length > 0) { finaldiscopath = discos[0]; } if (File.Exists(finalwsdlpath) && File.Exists(finaldiscopath)) { string SharePointVersion = Helpers.GetInstalledSharePointVersion(); //replace text in the files /*To register namespaces of the Windows SharePoint Services object model, open both the .disco and .wsdl files and replace the opening XML processing instruction -- <?xml version="1.0" encoding="utf-8"?> -- with instructions such as the following: <%@ Page Language="C#" Inherits="System.Web.UI.Page" %> <%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Import Namespace="Microsoft.SharePoint.Utilities" %> <%@ Import Namespace="Microsoft.SharePoint" %> <% Response.ContentType = "text/xml"; %> */ Helpers.ShowProgress(service, "Generating WSDL...", 90); StringBuilder wsdlreplaced = new StringBuilder(); TextReader wsdlreader = new StreamReader(finalwsdlpath); string input = null; while ((input = wsdlreader.ReadLine()) != null) { if (input.TrimStart(null).StartsWith("<?xml version=")) { wsdlreplaced.AppendLine("<%@ Page Language=\"C#\" Inherits=\"System.Web.UI.Page\" %>"); wsdlreplaced.AppendLine("<%@ Assembly Name=\"Microsoft.SharePoint, Version=" + SharePointVersion + ".0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" %>"); wsdlreplaced.AppendLine("<%@ Import Namespace=\"Microsoft.SharePoint.Utilities\" %> "); wsdlreplaced.AppendLine("<%@ Import Namespace=\"Microsoft.SharePoint\" %>"); wsdlreplaced.AppendLine("<% Response.ContentType = \"text/xml\"; %>"); } else if (input.TrimStart(null).StartsWith("<soap:address")) { wsdlreplaced.AppendLine("<soap:address location=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> />"); } else if (input.TrimStart(null).StartsWith("<soap12:address")) { wsdlreplaced.AppendLine("<soap12:address location=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> />"); } else { wsdlreplaced.AppendLine(input); } } wsdlreader.Close(); TextWriter wsdlwriter = new StreamWriter(finalwsdlpath); wsdlwriter.Write(wsdlreplaced.ToString()); wsdlwriter.Close(); StringBuilder discoreplaced = new StringBuilder(); TextReader discoreader = new StreamReader(finaldiscopath); string discoinput = null; while ((discoinput = discoreader.ReadLine()) != null) { if (discoinput.TrimStart(null).StartsWith("<?xml version=")) { discoreplaced.AppendLine("<%@ Page Language=\"C#\" Inherits=\"System.Web.UI.Page\" %>"); discoreplaced.AppendLine("<%@ Assembly Name=\"Microsoft.SharePoint, Version=" + SharePointVersion + ".0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" %>"); discoreplaced.AppendLine("<%@ Import Namespace=\"Microsoft.SharePoint.Utilities\" %> "); discoreplaced.AppendLine("<%@ Import Namespace=\"Microsoft.SharePoint\" %>"); discoreplaced.AppendLine("<% Response.ContentType = \"text/xml\"; %>"); } else if (discoinput.TrimStart(null).StartsWith("<contractRef")) { discoreplaced.AppendLine("<contractRef ref=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request) + \"?wsdl\"),Response.Output); %> docRef=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> xmlns=\"http://schemas.xmlsoap.org/disco/scl/\" />"); } else if (discoinput.TrimStart(null).StartsWith("<soap address=")) { //before //<soap address="http://tfsrtm08/_layouts/WebService1.asmx" xmlns:q1="http://SMC.Supernet.Web.WebServices/" binding="q1:WebService1Soap" xmlns="http://schemas.xmlsoap.org/disco/soap/" /> //replaced //<soap address=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> xmlns:q1="http://tempuri.org/" binding="q1:HelloWorld" xmlns="http://schemas.xmlsoap.org/disco/soap/" /> //we replace the field adress string originalstring = discoinput; string beforeaddress = originalstring.Substring(0, originalstring.IndexOf(" address=") + 9); string afteraddress = originalstring.Substring(originalstring.IndexOf("\"", originalstring.IndexOf(" address=") + 11)); //skip the quot afteraddress = afteraddress.Substring(1); discoreplaced.AppendLine(beforeaddress + "<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %>" + afteraddress); } else { discoreplaced.AppendLine(discoinput); } } discoreader.Close(); TextWriter discowriter = new StreamWriter(finaldiscopath); discowriter.Write(discoreplaced.ToString()); discowriter.Close(); //files renaming needed //WebService.wsdl -> WebServiceWSDL.aspx //WebService.disco -> WebServiceDisco.aspx string renamedwsdlpath = Path.Combine(workingDirectory, asmxfilenamewithoutext + "WSDL.aspx"); string renameddiscopath = Path.Combine(workingDirectory, asmxfilenamewithoutext + "Disco.aspx"); File.Copy(finalwsdlpath, renamedwsdlpath); File.Copy(finaldiscopath, renameddiscopath); //add the files to the project ProjectItem wsdlItem = Helpers.AddFile(asmxfileParentFolder, renamedwsdlpath); ProjectItem discoItem = Helpers.AddFile(asmxfileParentFolder, renameddiscopath); //set the deployment target of the files to the same as the parent if (Helpers2.IsSharePointVSTemplate(service, project)) { Helpers2.CopyDeploymentPath(WebServiceFile, wsdlItem); Helpers2.CopyDeploymentPath(WebServiceFile, discoItem); } } else { string message = "Created WSDL and DISCO files not found. Creation failed."; Helpers.LogMessage(service, this, message); MessageBox.Show(message); } try { //delete temp folder Directory.Delete(workingDirectory, true); //clean up everything what we have copied to the layouts folder if (ASMXFileExisted) { File.Delete(fullasmxtarget); } } catch (Exception) { } Helpers.HideProgress(service); } /// <summary> /// Removes the previously added reference, if it was created /// </summary> public override void Undo() { } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using PlacesAPI.Areas.HelpPage.ModelDescriptions; using PlacesAPI.Areas.HelpPage.Models; namespace PlacesAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// BackupJobsOperations operations. /// </summary> internal partial class BackupJobsOperations : IServiceOperations<RecoveryServicesBackupClient>, IBackupJobsOperations { /// <summary> /// Initializes a new instance of the BackupJobsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal BackupJobsOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Provides a pageable list of jobs. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='skipToken'> /// skipToken Filter. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<JobResource>>> ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, ODataQuery<JobQueryObject> odataQuery = default(ODataQuery<JobQueryObject>), string skipToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("skipToken", skipToken); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupJobs").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (skipToken != null) { _queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<JobResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<JobResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Provides a pageable list of jobs. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<JobResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<JobResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<JobResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using Xunit; using FluentAssertions; using EmsApi.Client.V2; namespace EmsApi.Tests { public class AuthenticationTrustedTests : TestBase { [Fact( DisplayName = "Client id but no client secret should fail" )] public void Client_id_but_no_secret_should_fail() { EmsApiServiceConfiguration config = m_config.Clone(); config.UserName = null; config.Password = null; config.ApiClientId = "foobarbaz"; config.ApiClientSecret = null; Action create = () => _ = new EmsApiService( config ); create.Should().Throw<EmsApiConfigurationException>(); } [Fact( DisplayName = "Client secret but no id should fail" )] public void Client_secret_but_no_id_should_fail() { EmsApiServiceConfiguration config = m_config.Clone(); config.UserName = null; config.Password = null; config.ApiClientId = null; config.ApiClientSecret = "not so secret"; Action create = () => _ = new EmsApiService( config ); create.Should().Throw<EmsApiConfigurationException>(); } [Fact( DisplayName = "Trusted value but no name should fail" )] public void Trusted_value_but_no_name() { using var service = NewService(); var ctx = new CallContext { TrustedAuthValue = "emsapitest" }; Action getSystem = () => service.EmsSystem.Get( ctx ); getSystem.Should().Throw<EmsApiException>(); } [Fact( DisplayName = "Trusted info but no client id should fail" )] public void Trusted_info_but_no_client_id() { EmsApiServiceConfiguration config = m_config.Clone(); config.ApiClientId = null; config.ApiClientSecret = null; using var service = new EmsApiService( config ); var ctx = new CallContext { TrustedAuthName = "SAMAccountName", TrustedAuthValue = "emsapitest" }; Action getSystem = () => service.EmsSystem.Get( ctx ); getSystem.Should().Throw<EmsApiException>(); } [Fact( DisplayName = "Trusted name but no value should fail" )] public void Trusted_name_but_no_value() { using var service = NewService(); var ctx = new CallContext { TrustedAuthName = "propertyX" }; Action getSystem = () => service.EmsSystem.Get( ctx ); getSystem.Should().Throw<EmsApiException>(); } [Fact( DisplayName = "Trusted info in context should succeed" )] public void Trusted_info_in_context() { using var service = NewService(); var ctx = new CallContext { TrustedAuthName = "SAMAccountName", TrustedAuthValue = "emsapitest" }; var system = service.EmsSystem.Get( ctx ); system.Id.Should().Be( 1 ); service.HasAuthenticatedWithTrusted( ctx.TrustedAuthName, ctx.TrustedAuthValue ).Should().BeTrue(); service.Authenticated.Should().BeFalse(); } [Fact( DisplayName = "Trusted value in context and name in config should succeed" )] public void Trusted_value_in_context_name_in_config() { EmsApiServiceConfiguration config = m_config.Clone(); config.TrustedAuthName = "SAMAccountName"; using var service = new EmsApiService( config ); var ctx = new CallContext { TrustedAuthValue = "emsapitest" }; var system = service.EmsSystem.Get( ctx ); system.Id.Should().Be( 1 ); service.HasAuthenticatedWithTrusted( config.TrustedAuthName, ctx.TrustedAuthValue ).Should().BeTrue(); service.Authenticated.Should().BeFalse(); } [Fact( DisplayName = "Trusted and then password both work" )] public void Trusted_then_password() { using var service = NewService(); // First perform the trusted auth. var ctx = new CallContext { TrustedAuthName = "SAMAccountName", TrustedAuthValue = "emsapitest" }; var system = service.EmsSystem.Get( ctx ); system.Id.Should().Be( 1 ); service.HasAuthenticatedWithTrusted( ctx.TrustedAuthName, ctx.TrustedAuthValue ).Should().BeTrue(); service.Authenticated.Should().BeFalse(); // Then perform the password auth. system = service.EmsSystem.Get(); system.Id.Should().Be( 1 ); service.Authenticated.Should().BeTrue(); } [Fact( DisplayName = "Password and then trusted both work" )] public void Password_then_trusted() { using var service = NewService(); var ctx = new CallContext { TrustedAuthName = "SAMAccountName", TrustedAuthValue = "emsapitest" }; // First perform the password auth. var system = service.EmsSystem.Get(); system.Id.Should().Be( 1 ); service.Authenticated.Should().BeTrue(); service.HasAuthenticatedWithTrusted( ctx.TrustedAuthName, ctx.TrustedAuthValue ).Should().BeFalse(); // Then perform the trusted auth. system = service.EmsSystem.Get( ctx ); system.Id.Should().Be( 1 ); service.HasAuthenticatedWithTrusted( ctx.TrustedAuthName, ctx.TrustedAuthValue ).Should().BeTrue(); } [Fact( DisplayName = "Authentication cache" )] public void Auth_cache() { var lastHandler = new TestMessageHandler(); using var service = NewService( new EmsApiServiceHttpClientConfiguration { LastHandler = lastHandler } ); var ctx = new CallContext { TrustedAuthName = "SAMAccountName", TrustedAuthValue = "emsapitest" }; var ctx2 = new CallContext { TrustedAuthName = "SAMAccountName", TrustedAuthValue = "emsweb" }; // First perform the password auth - CACHE MISS var system = service.EmsSystem.Get(); lastHandler.CallCount.Should().Be( 2 ); // One for the token and one for our actual call. system.Id.Should().Be( 1 ); service.Authenticated.Should().BeTrue(); service.HasAuthenticatedWithTrusted( ctx.TrustedAuthName, ctx.TrustedAuthValue ).Should().BeFalse(); // Then perform the trusted auth - CACHE MISS system = service.EmsSystem.Get( ctx ); lastHandler.CallCount.Should().Be( 4 ); // One for the token and one for our actual call. system.Id.Should().Be( 1 ); service.HasAuthenticatedWithTrusted( ctx.TrustedAuthName, ctx.TrustedAuthValue ).Should().BeTrue(); service.HasAuthenticatedWithTrusted( ctx2.TrustedAuthName, ctx2.TrustedAuthValue ).Should().BeFalse(); // Then perform the trusted auth 2 - CACHE MISS system = service.EmsSystem.Get( ctx2 ); lastHandler.CallCount.Should().Be( 6 ); // One for the token and one for our actual call. system.Id.Should().Be( 1 ); service.HasAuthenticatedWithTrusted( ctx2.TrustedAuthName, ctx2.TrustedAuthValue ).Should().BeTrue(); // Then perform the three calls again - CACHE HIT system = service.EmsSystem.Get( ctx2 ); lastHandler.CallCount.Should().Be( 7 ); system = service.EmsSystem.Get( ctx ); lastHandler.CallCount.Should().Be( 8 ); system = service.EmsSystem.Get(); lastHandler.CallCount.Should().Be( 9 ); // Clear the cache and make a few more calls on one authentication path. service.ClearAuthenticationCache(); system = service.EmsSystem.Get( ctx2 ); lastHandler.CallCount.Should().Be( 11 ); // One for the token and one for our actual call. system = service.EmsSystem.Get( ctx2 ); lastHandler.CallCount.Should().Be( 12 ); // Expire the tokens and make a few more calls on one authentication path. service.ExpireAuthenticationCacheEntries(); system = service.EmsSystem.Get( ctx2 ); lastHandler.CallCount.Should().Be( 14 ); // One for the token and one for our actual call. system = service.EmsSystem.Get( ctx2 ); lastHandler.CallCount.Should().Be( 15 ); } } }
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1) #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using Newtonsoft.Json.Utilities; using System.Diagnostics; using System.Globalization; namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a JSON property. /// </summary> public class JProperty : JContainer { private readonly List<JToken> _content = new List<JToken>(); private readonly string _name; /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens { get { return _content; } } /// <summary> /// Gets the property name. /// </summary> /// <value>The property name.</value> public string Name { [DebuggerStepThrough] get { return _name; } } #pragma warning disable 108 /// <summary> /// Gets or sets the property value. /// </summary> /// <value>The property value.</value> public JToken Value { [DebuggerStepThrough] get { return (ChildrenTokens.Count > 0) ? ChildrenTokens[0] : null; } set { CheckReentrancy(); JToken newValue = value ?? new JValue((object) null); if (ChildrenTokens.Count == 0) { InsertItem(0, newValue); } else { SetItem(0, newValue); } } } #pragma warning restore 108 /// <summary> /// Initializes a new instance of the <see cref="JProperty"/> class from another <see cref="JProperty"/> object. /// </summary> /// <param name="other">A <see cref="JProperty"/> object to copy from.</param> public JProperty(JProperty other) : base(other) { _name = other.Name; } internal override JToken GetItem(int index) { if (index != 0) throw new ArgumentOutOfRangeException(); return Value; } internal override void SetItem(int index, JToken item) { if (index != 0) throw new ArgumentOutOfRangeException(); if (IsTokenUnchanged(Value, item)) return; if (Parent != null) ((JObject)Parent).InternalPropertyChanging(this); base.SetItem(0, item); if (Parent != null) ((JObject)Parent).InternalPropertyChanged(this); } internal override bool RemoveItem(JToken item) { throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } internal override void RemoveItemAt(int index) { throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } internal override void InsertItem(int index, JToken item) { if (Value != null) throw new Exception("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); base.InsertItem(0, item); } internal override bool ContainsItem(JToken item) { return (Value == item); } internal override void ClearItems() { throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } internal override bool DeepEquals(JToken node) { JProperty t = node as JProperty; return (t != null && _name == t.Name && ContentsEqual(t)); } internal override JToken CloneToken() { return new JProperty(this); } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type { [DebuggerStepThrough] get { return JTokenType.Property; } } internal JProperty(string name) { // called from JTokenWriter ValidationUtils.ArgumentNotNull(name, "name"); _name = name; } /// <summary> /// Initializes a new instance of the <see cref="JProperty"/> class. /// </summary> /// <param name="name">The property name.</param> /// <param name="content">The property content.</param> public JProperty(string name, params object[] content) : this(name, (object)content) { } /// <summary> /// Initializes a new instance of the <see cref="JProperty"/> class. /// </summary> /// <param name="name">The property name.</param> /// <param name="content">The property content.</param> public JProperty(string name, object content) { ValidationUtils.ArgumentNotNull(name, "name"); _name = name; Value = IsMultiContent(content) ? new JArray(content) : CreateFromContent(content); } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WritePropertyName(_name); Value.WriteTo(writer, converters); } internal override int GetDeepHashCode() { return _name.GetHashCode() ^ ((Value != null) ? Value.GetDeepHashCode() : 0); } /// <summary> /// Loads an <see cref="JProperty"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JProperty"/>.</param> /// <returns>A <see cref="JProperty"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public static new JProperty Load(JsonReader reader) { if (reader.TokenType == JsonToken.None) { if (!reader.Read()) throw new Exception("Error reading JProperty from JsonReader."); } if (reader.TokenType != JsonToken.PropertyName) throw new Exception( "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith( CultureInfo.InvariantCulture, reader.TokenType)); JProperty p = new JProperty((string)reader.Value); p.SetLineInfo(reader as IJsonLineInfo); p.ReadTokenFrom(reader); return p; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; namespace System.Collections.Specialized.Tests { public class OrderedDictionaryTests { // public OrderedDictionary(); [Fact] public void DefaultConstructorDoesNotThrow() { OrderedDictionary dictionary = new OrderedDictionary(); } // public OrderedDictionary(int capacity); [Fact] public void CreatingWithDifferentCapacityValues() { // exceptions are not thrown until you add an element var d1 = new OrderedDictionary(-1000); var d2 = new OrderedDictionary(-1); var d3 = new OrderedDictionary(0); var d4 = new OrderedDictionary(1); var d5 = new OrderedDictionary(1000); Assert.Throws<ArgumentOutOfRangeException>(() => d1.Add("foo", "bar")); Assert.Throws<ArgumentOutOfRangeException>(() => d2.Add("foo", "bar")); d3.Add("foo", "bar"); d4.Add("foo", "bar"); d5.Add("foo", "bar"); } // public OrderedDictionary(IEqualityComparer comparer); [Fact] public void PassingEqualityComparers() { var eqComp = new CaseInsensitiveEqualityComparer(); var d1 = new OrderedDictionary(eqComp); d1.Add("foo", "bar"); AssertExtensions.Throws<ArgumentException>(null, () => d1.Add("FOO", "bar")); // The equality comparer should also test for a non-existent key d1.Remove("foofoo"); Assert.True(d1.Contains("foo")); // Make sure we can change an existent key that passes the equality comparer d1["FOO"] = "barbar"; Assert.Equal("barbar", d1["foo"]); d1.Remove("FOO"); Assert.False(d1.Contains("foo")); } // public OrderedDictionary(int capacity, IEqualityComparer comparer); [Fact] public void PassingCapacityAndIEqualityComparer() { var eqComp = new CaseInsensitiveEqualityComparer(); var d1 = new OrderedDictionary(-1000, eqComp); var d2 = new OrderedDictionary(-1, eqComp); var d3 = new OrderedDictionary(0, eqComp); var d4 = new OrderedDictionary(1, eqComp); var d5 = new OrderedDictionary(1000, eqComp); Assert.Throws<ArgumentOutOfRangeException>(() => d1.Add("foo", "bar")); Assert.Throws<ArgumentOutOfRangeException>(() => d2.Add("foo", "bar")); d3.Add("foo", "bar"); d4.Add("foo", "bar"); d5.Add("foo", "bar"); } // public int Count { get; } [Fact] public void CountTests() { var d = new OrderedDictionary(); Assert.Equal(0, d.Count); for (int i = 0; i < 1000; i++) { d.Add(i, i); Assert.Equal(i + 1, d.Count); } for (int i = 0; i < 1000; i++) { d.Remove(i); Assert.Equal(1000 - i - 1, d.Count); } for (int i = 0; i < 1000; i++) { d[(object)i] = i; Assert.Equal(i + 1, d.Count); } for (int i = 0; i < 1000; i++) { d.RemoveAt(0); Assert.Equal(1000 - i - 1, d.Count); } } // public bool IsReadOnly { get; } [Fact] public void IsReadOnlyTests() { var d = new OrderedDictionary(); Assert.False(d.IsReadOnly); var d2 = d.AsReadOnly(); Assert.True(d2.IsReadOnly); } [Fact] public void AsReadOnly_AttemptingToModifyDictionary_Throws() { OrderedDictionary orderedDictionary = new OrderedDictionary().AsReadOnly(); Assert.Throws<NotSupportedException>(() => orderedDictionary[0] = "value"); Assert.Throws<NotSupportedException>(() => orderedDictionary["key"] = "value"); Assert.Throws<NotSupportedException>(() => orderedDictionary.Add("key", "value")); Assert.Throws<NotSupportedException>(() => orderedDictionary.Insert(0, "key", "value")); Assert.Throws<NotSupportedException>(() => orderedDictionary.Remove("key")); Assert.Throws<NotSupportedException>(() => orderedDictionary.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => orderedDictionary.Clear()); } // public ICollection Keys { get; } [Fact] public void KeysPropertyContainsAllKeys() { var d = new OrderedDictionary(); var alreadyChecked = new bool[1000]; for (int i = 0; i < 1000; i++) { d["test_" + i] = i; alreadyChecked[i] = false; } ICollection keys = d.Keys; Assert.False(keys.IsSynchronized); Assert.NotSame(d, keys.SyncRoot); Assert.Equal(d.Count, keys.Count); foreach (var key in d.Keys) { string skey = (string)key; var p = skey.Split(new char[] { '_' }); Assert.Equal(2, p.Length); int number = int.Parse(p[1]); Assert.False(alreadyChecked[number]); Assert.True(number >= 0 && number < 1000); alreadyChecked[number] = true; } object[] array = new object[keys.Count + 50]; keys.CopyTo(array, 50); for (int i = 50; i < array.Length; i++) { Assert.True(d.Contains(array[i])); } AssertExtensions.Throws<ArgumentNullException>("array", () => keys.CopyTo(null, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => keys.CopyTo(new object[keys.Count], -1)); } // bool System.Collections.ICollection.IsSynchronized { get; } [Fact] public void IsSynchronizedTests() { ICollection c = new OrderedDictionary(); Assert.False(c.IsSynchronized); } [Fact] public void SyncRootTests() { ICollection orderedDictionary1 = new OrderedDictionary(); ICollection orderedDictionary2 = new OrderedDictionary(); object sync1 = orderedDictionary1.SyncRoot; object sync2 = orderedDictionary2.SyncRoot; // Sync root objects for the same dictionaries are equivalent Assert.Same(orderedDictionary1.SyncRoot, orderedDictionary1.SyncRoot); Assert.Same(orderedDictionary2.SyncRoot, orderedDictionary2.SyncRoot); // Sync root objects for different dictionaries are not equivalent Assert.NotSame(sync1, sync2); } // bool System.Collections.IDictionary.IsFixedSize { get; } [Fact] public void IsFixedSizeTests() { var d = new OrderedDictionary(); IDictionary dic = d; IDictionary rodic = d.AsReadOnly(); Assert.False(dic.IsFixedSize); Assert.True(rodic.IsFixedSize); } // public object this[int index] { get; set; } [Fact] public void GettingByIndexTests() { var d = new OrderedDictionary(); for (int i = 0; i < 1000; i++) { d.Add("test" + i, i); } for (int i = 0; i < 1000; i++) { Assert.Equal(d[i], i); d[i] = (int)d[i] + 100; Assert.Equal(d[i], 100 + i); } Assert.Throws<ArgumentOutOfRangeException>(() => { int foo = (int)d[-1]; }); Assert.Throws<ArgumentOutOfRangeException>(() => { d[-1] = 5; }); Assert.Throws<ArgumentOutOfRangeException>(() => { int foo = (int)d[1000]; }); Assert.Throws<ArgumentOutOfRangeException>(() => { d[1000] = 5; }); } // public object this[object key] { get; set; } [Fact] public void GettingByKeyTests() { var d = new OrderedDictionary(); for (int i = 0; i < 1000; i++) { d.Add("test" + i, i); } for (int i = 0; i < 1000; i++) { Assert.Equal(d["test" + i], i); d["test" + i] = (int)d["test" + i] + 100; Assert.Equal(d["test" + i], 100 + i); } for (int i = 1000; i < 2000; i++) { d["test" + i] = 1337; } Assert.Equal(null, d["asdasd"]); Assert.Throws<ArgumentNullException>(() => { var a = d[null]; }); Assert.Throws<ArgumentNullException>(() => { d[null] = 1337; }); } // public ICollection Values { get; } [Fact] public void ValuesPropertyContainsAllValues() { var d = new OrderedDictionary(); var alreadyChecked = new bool[1000]; for (int i = 0; i < 1000; i++) { d["foo" + i] = "bar_" + i; alreadyChecked[i] = false; } ICollection values = d.Values; Assert.False(values.IsSynchronized); Assert.NotSame(d, values.SyncRoot); Assert.Equal(d.Count, values.Count); foreach (var val in values) { string sval = (string)val; var p = sval.Split(new char[] { '_' }); Assert.Equal(2, p.Length); int number = int.Parse(p[1]); Assert.False(alreadyChecked[number]); Assert.True(number >= 0 && number < 1000); alreadyChecked[number] = true; } object[] array = new object[values.Count + 50]; values.CopyTo(array, 50); for (int i = 50; i < array.Length; i++) { Assert.Equal(array[i], "bar_" + (i - 50)); } AssertExtensions.Throws<ArgumentNullException>("array", () => values.CopyTo(null, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => values.CopyTo(new object[values.Count], -1)); } // public void Add(object key, object value); [Fact] public void AddTests() { var d = new OrderedDictionary(); d.Add((int)5, "foo1"); Assert.Equal("foo1", d[(object)((int)5)]); d.Add((double)5, "foo2"); Assert.Equal("foo2", d[(object)((double)5)]); d.Add((long)5, "foo3"); Assert.Equal("foo3", d[(object)((long)5)]); d.Add((short)5, "foo4"); Assert.Equal("foo4", d[(object)((short)5)]); d.Add((uint)5, "foo5"); Assert.Equal("foo5", d[(object)((uint)5)]); d.Add("5", "foo6"); Assert.Equal("foo6", d["5"]); AssertExtensions.Throws<ArgumentException>(null, () => d.Add((int)5, "foo")); AssertExtensions.Throws<ArgumentException>(null, () => d.Add((double)5, "foo")); AssertExtensions.Throws<ArgumentException>(null, () => d.Add((long)5, "foo")); AssertExtensions.Throws<ArgumentException>(null, () => d.Add((short)5, "foo")); AssertExtensions.Throws<ArgumentException>(null, () => d.Add((uint)5, "foo")); AssertExtensions.Throws<ArgumentException>(null, () => d.Add("5", "foo")); Assert.Throws<ArgumentNullException>(() => d.Add(null, "foobar")); } // public OrderedDictionary AsReadOnly(); [Fact] public void AsReadOnlyTests() { var _d = new OrderedDictionary(); _d["foo"] = "bar"; _d[(object)13] = 37; var d = _d.AsReadOnly(); Assert.True(d.IsReadOnly); Assert.Equal("bar", d["foo"]); Assert.Equal(37, d[(object)13]); Assert.Throws<NotSupportedException>(() => { d["foo"] = "moooooooooaaah"; }); Assert.Throws<NotSupportedException>(() => { d["asdasd"] = "moooooooooaaah"; }); Assert.Equal(null, d["asdasd"]); Assert.Throws<ArgumentNullException>(() => { var a = d[null]; }); } // public void Clear(); [Fact] public void ClearTests() { var d = new OrderedDictionary(); d.Clear(); Assert.Equal(0, d.Count); for (int i = 0; i < 1000; i++) { d.Add(i, i); } d.Clear(); Assert.Equal(0, d.Count); d.Clear(); Assert.Equal(0, d.Count); for (int i = 0; i < 1000; i++) { d.Add("foo", "bar"); d.Clear(); Assert.Equal(0, d.Count); } } // public bool Contains(object key); [Fact] public void ContainsTests() { var d = new OrderedDictionary(); Assert.Throws<ArgumentNullException>(() => d.Contains(null)); Assert.False(d.Contains("foo")); for (int i = 0; i < 1000; i++) { var k = "test_" + i; d.Add(k, "asd"); Assert.True(d.Contains(k)); // different reference Assert.True(d.Contains("test_" + i)); } Assert.False(d.Contains("foo")); } // public void CopyTo(Array array, int index); [Fact] public void CopyToTests() { var d = new OrderedDictionary(); d["foo"] = "bar"; d[" "] = "asd"; DictionaryEntry[] arr = new DictionaryEntry[3]; Assert.Throws<ArgumentNullException>(() => d.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => d.CopyTo(arr, -1)); AssertExtensions.Throws<ArgumentException>(null, () => d.CopyTo(arr, 3)); d.CopyTo(arr, 0); for (int i = 0; i < 2; i++) { Assert.True(d.Contains(arr[i].Key)); Assert.Equal(d[arr[i].Key], arr[i].Value); } Assert.NotEqual(arr[0].Key, arr[1].Key); d.CopyTo(arr, 1); for (int i = 1; i < 3; i++) { Assert.True(d.Contains(arr[i].Key)); Assert.Equal(d[arr[i].Key], arr[i].Value); } Assert.NotEqual(arr[1].Key, arr[2].Key); } [Fact] public void GetDictionaryEnumeratorTests() { var d = new OrderedDictionary(); for (int i = 0; i < 10; i++) { d.Add("Key_" + i, "Value_" + i); } IDictionaryEnumerator e = d.GetEnumerator(); for (int i = 0; i < 2; i++) { int count = 0; while (e.MoveNext()) { DictionaryEntry entry1 = (DictionaryEntry)e.Current; DictionaryEntry entry2 = e.Entry; Assert.Equal(entry1.Key, entry2.Key); Assert.Equal(entry1.Value, entry1.Value); Assert.Equal(e.Key, entry1.Key); Assert.Equal(e.Value, entry1.Value); Assert.Equal(e.Value, d[e.Key]); count++; } Assert.Equal(count, d.Count); Assert.False(e.MoveNext()); e.Reset(); } e = d.GetEnumerator(); d["foo"] = "bar"; Assert.Throws<InvalidOperationException>(() => e.MoveNext()); } [Fact] public void GetEnumeratorTests() { var d = new OrderedDictionary(); for (int i = 0; i < 10; i++) { d.Add("Key_" + i, "Value_" + i); } IEnumerator e = ((ICollection)d).GetEnumerator(); for (int i = 0; i < 2; i++) { int count = 0; while (e.MoveNext()) { DictionaryEntry entry = (DictionaryEntry)e.Current; Assert.Equal(entry.Value, d[entry.Key]); count++; } Assert.Equal(count, d.Count); Assert.False(e.MoveNext()); e.Reset(); } } // public void Insert(int index, object key, object value); [Fact] public void InsertTests() { var d = new OrderedDictionary(); Assert.Throws<ArgumentOutOfRangeException>(() => d.Insert(-1, "foo", "bar")); Assert.Throws<ArgumentNullException>(() => d.Insert(0, null, "bar")); Assert.Throws<ArgumentOutOfRangeException>(() => d.Insert(1, "foo", "bar")); d.Insert(0, "foo", "bar"); Assert.Equal("bar", d["foo"]); Assert.Equal("bar", d[0]); AssertExtensions.Throws<ArgumentException>(null, () => d.Insert(0, "foo", "bar")); d.Insert(0, "aaa", "bbb"); Assert.Equal("bbb", d["aaa"]); Assert.Equal("bbb", d[0]); d.Insert(0, "zzz", "ccc"); Assert.Equal("ccc", d["zzz"]); Assert.Equal("ccc", d[0]); d.Insert(3, "13", "37"); Assert.Equal("37", d["13"]); Assert.Equal("37", d[3]); } // public void Remove(object key); [Fact] public void RemoveTests() { var d = new OrderedDictionary(); // should work d.Remove("asd"); Assert.Throws<ArgumentNullException>(() => d.Remove(null)); for (var i = 0; i < 1000; i++) { d.Add("foo_" + i, "bar_" + i); } for (var i = 0; i < 1000; i++) { Assert.True(d.Contains("foo_" + i)); d.Remove("foo_" + i); Assert.False(d.Contains("foo_" + i)); Assert.Equal(1000 - i - 1, d.Count); } } // public void RemoveAt(int index); [Fact] public void RemoveAtTests() { var d = new OrderedDictionary(); Assert.Throws<ArgumentOutOfRangeException>(() => d.RemoveAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => d.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => d.RemoveAt(5)); Assert.Throws<ArgumentNullException>(() => d.Remove(null)); for (var i = 0; i < 1000; i++) { d.Add("foo_" + i, "bar_" + i); } for (var i = 0; i < 1000; i++) { d.RemoveAt(1000 - i - 1); Assert.Equal(1000 - i - 1, d.Count); } for (var i = 0; i < 1000; i++) { d.Add("foo_" + i, "bar_" + i); } for (var i = 0; i < 1000; i++) { Assert.Equal("bar_" + i, d[0]); d.RemoveAt(0); Assert.Equal(1000 - i - 1, d.Count); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using PdfService.Areas.HelpPage.Models; namespace PdfService.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Diagnostics; using System.Drawing; using System.IO; using DevExpress.Internal.WinApi; using DevExpress.Internal.WinApi.Window.Data.Xml.Dom; using DevExpress.Internal.WinApi.Windows.UI.Notifications; namespace DevExpress.Internal { class WinRTToastNotificationContent : IPredefinedToastNotificationContent, IPredefinedToastNotificationContentGeneric { string[] lines = new string[3]; ToastTemplateType type; string imagePath; internal string tempImagePath; string appLogoImagePath; string tempAppLogoImagePath; string heroImagePath; string tempHeroImagePath; ImageCropType appLogoImageCrop; PredefinedSound sound; NotificationDuration duration = NotificationDuration.Default; string attributionText = string.Empty; DateTimeOffset? displayTimestamp = null; WinRTToastNotificationContent() { } public void Dispose() { RemoveTempFile(tempImagePath); tempImagePath = null; RemoveTempFile(tempAppLogoImagePath); tempAppLogoImagePath = null; RemoveTempFile(tempHeroImagePath); tempHeroImagePath = null; updateToastContent = null; } public static WinRTToastNotificationContent Create(string bodyText) { return Create(ToastTemplateType.ToastText01, bodyText); } public static WinRTToastNotificationContent CreateOneLineHeader(string headlineText, string bodyText) { return Create(ToastTemplateType.ToastText02, headlineText, bodyText); } public static WinRTToastNotificationContent CreateTwoLineHeader(string headlineText, string bodyText) { return Create(ToastTemplateType.ToastText03, headlineText, bodyText); } public static WinRTToastNotificationContent CreateOneLineHeader(string headlineText, string bodyText1, string bodyText2) { return Create(ToastTemplateType.ToastText04, headlineText, bodyText1, bodyText2); } public static WinRTToastNotificationContent CreateToastGeneric(string headlineText, string bodyText1, string bodyText2) { return Create(ToastTemplateType.ToastGeneric, headlineText, bodyText1, bodyText2); } static WinRTToastNotificationContent Create(ToastTemplateType type, params string[] lines) { return new WinRTToastNotificationContent { type = type, lines = lines }; } static void SetNodeValueString(string str, IXmlDocument xmldoc, IXmlNode node) { IXmlText textNode; using(var hStrign_str = HSTRING.FromString(str)) ComFunctions.CheckHRESULT(xmldoc.CreateTextNode(hStrign_str, out textNode)); AppendNode(node, (IXmlNode)textNode); } static void SetImageSrc(IXmlDocument xmldoc, string imagePath) { IXmlNode imageNode = GetNode(xmldoc, "image"); IXmlNode srcAttribute; using(var hString_name = HSTRING.FromString("src")) ComFunctions.CheckHRESULT(imageNode.Attributes.GetNamedItem(hString_name, out srcAttribute)); SetNodeValueString(imagePath, xmldoc, srcAttribute); } public void SetAppLogoImageCrop(ImageCropType appLogoImageCrop) { this.appLogoImageCrop = appLogoImageCrop; } public void SetSound(PredefinedSound sound) { this.sound = sound; } public void SetDuration(NotificationDuration duration) { this.duration = duration; } public void SetAttributionText(string attributionText) { this.attributionText = attributionText; } public void SetDisplayTimestamp(DateTimeOffset? displayTimestamp) { this.displayTimestamp = displayTimestamp; } public void SetImage(string imagePath) { SetImage(imagePath, ImagePlacement.Inline); } public void SetImage(string imagePath, ImagePlacement placement) { CheckImagePath(imagePath); switch(placement) { case ImagePlacement.Inline: UpdateTemplateType(); this.imagePath = imagePath; break; case ImagePlacement.AppLogo: this.appLogoImagePath = imagePath; break; case ImagePlacement.Hero: this.heroImagePath = imagePath; break; } } void UpdateTemplateType() { if(type != ToastTemplateType.ToastGeneric) { if(type == ToastTemplateType.ToastText01) type = ToastTemplateType.ToastImageAndText01; if(type == ToastTemplateType.ToastText02) type = ToastTemplateType.ToastImageAndText02; if(type == ToastTemplateType.ToastText03) type = ToastTemplateType.ToastImageAndText03; if(type == ToastTemplateType.ToastText04) type = ToastTemplateType.ToastImageAndText04; } else if(!ToastNotificationManager.IsGenericTemplateSupported) type = ToastTemplateType.ToastImageAndText04; } public void SetImage(byte[] image) { SetImage(new MemoryStream(image)); } public void SetImage(Stream stream) { SetImage(Image.FromStream(stream)); } public void SetImage(Image image) { SetImage(image, ImagePlacement.Inline); } public void SetImage(Image image, ImagePlacement placement) { string imagePath = GetTempPath(); switch(placement) { case ImagePlacement.Inline: if(tempImagePath != null) { RemoveTempFile(tempImagePath); tempImagePath = null; } tempImagePath = imagePath; break; case ImagePlacement.AppLogo: if(tempAppLogoImagePath != null) { RemoveTempFile(tempAppLogoImagePath); tempAppLogoImagePath = null; } tempAppLogoImagePath = imagePath; break; case ImagePlacement.Hero: if(tempHeroImagePath != null) { RemoveTempFile(tempHeroImagePath); tempHeroImagePath = null; } tempHeroImagePath = imagePath; break; } SaveImageToFile(image, imagePath); SetImage(imagePath, placement); } static string GetTempPath() { string tempPath = Path.GetTempPath(); string result = string.Empty; do { result = tempPath + Guid.NewGuid().ToString() + ".png"; } while(File.Exists(result)); return result; } void SaveImageToFile(Image image, string path) { image.Save(path, System.Drawing.Imaging.ImageFormat.Png); } bool IsSupportedExtension(string imagePath) { var extensions = new string[] { ".png", ".jpg", ".jpeg", ".gif" }; string fileExt = Path.GetExtension(imagePath); foreach(string goodExt in extensions) { if(fileExt.Equals(goodExt, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } void CheckImagePath(string imagePath) { FileInfo info = new FileInfo(imagePath); if(!info.Exists) return; if(!IsSupportedExtension(info.Extension)) throw new ArgumentException("Unsupported file type"); if(info.Length > 1024 * 200) { if(!Utils.WindowsVersionProvider.IsWin10FallCreatorsUpdateOrHigher) { throw new ArgumentException("File must have size less or equal to 200 KB"); } } } static bool IsLoopingSound(PredefinedSound sound) { return sound >= PredefinedSound.Notification_Looping_Alarm; } Action<System.Xml.XmlDocument> updateToastContent = null; public void SetUpdateToastContentAction(Action<System.Xml.XmlDocument> updateToastContentAction) { updateToastContent = updateToastContentAction; } public IPredefinedToastNotificationInfo Info { get { return new WinRTToastNotificationInfo() { ToastTemplateType = type, Lines = lines, ImagePath = imagePath, AppLogoImagePath = appLogoImagePath, HeroImagePath = heroImagePath, AppLogoImageCrop = appLogoImageCrop, Duration = duration, Sound = sound, AttributionText = attributionText, DisplayTimestamp = displayTimestamp, UpdateToastContent = updateToastContent }; } } class WinRTToastNotificationInfo : IPredefinedToastNotificationInfo, IPredefinedToastNotificationInfoGeneric { public ToastTemplateType ToastTemplateType { get; set; } public string[] Lines { get; set; } public string ImagePath { get; set; } public string AppLogoImagePath { get; set; } public string HeroImagePath { get; set; } public ImageCropType AppLogoImageCrop { get; set; } public NotificationDuration Duration { get; set; } public PredefinedSound Sound { get; set; } public string AttributionText { get; set; } public DateTimeOffset? DisplayTimestamp { get; set; } public Action<System.Xml.XmlDocument> UpdateToastContent { get; set; } } internal static IXmlDocument GetDocument(IToastNotificationManager manager, IPredefinedToastNotificationInfo info) { var content = manager.GetTemplateContent(GetToastTemplateType(info)); if(ToastNotificationManager.IsGenericTemplateSupported) { UpdateTemplate(content, info); UpdateAttributionText(content, info); UpdateDisplayTimestamp(content, info); UpdateAppLogoImage(info, content); UpdateHeroImage(info, content); } UpdateText(content, info); UpdateInlineImage(info, content); UpdateSound(content, info); UpdateDuration(content, info); UpdateContent(content, info); return content; } static void UpdateContent(IXmlDocument xmldoc, IPredefinedToastNotificationInfo info) { string xml = ToastNotificationManager.GetXml((IXmlNodeSerializer)xmldoc); var document = new System.Xml.XmlDocument(); document.LoadXml(xml); IPredefinedToastNotificationInfoGeneric infoGeneric = info as IPredefinedToastNotificationInfoGeneric; if(infoGeneric.UpdateToastContent != null) infoGeneric.UpdateToastContent.Invoke(document); infoGeneric.UpdateToastContent = null; ToastNotificationManager.LoadXml((IXmlDocumentIO)xmldoc, document.OuterXml); } static ToastTemplateType GetToastTemplateType(IPredefinedToastNotificationInfo info) { if(info.ToastTemplateType != ToastTemplateType.ToastGeneric) return info.ToastTemplateType; return ToastTemplateType.ToastText04; } static void UpdateTemplate(IXmlDocument xmldoc, IPredefinedToastNotificationInfo info) { if(info.ToastTemplateType != ToastTemplateType.ToastGeneric) return; SetAttribute(xmldoc, "binding", "template", "ToastGeneric"); } static void UpdateText(IXmlDocument xmldoc, IPredefinedToastNotificationInfo info) { IXmlNodeList nodes = GetNodes(xmldoc, "text"); Debug.Assert(nodes.Length >= info.Lines.Length); for(uint i = 0; i < info.Lines.Length; i++) { SetNodeValueString(info.Lines[i] ?? string.Empty, xmldoc, GetNode(nodes, i)); } } static void UpdateAttributionText(IXmlDocument xmldoc, IPredefinedToastNotificationInfo info) { IPredefinedToastNotificationInfoGeneric infoGeneric = info as IPredefinedToastNotificationInfoGeneric; if(string.IsNullOrWhiteSpace(infoGeneric.AttributionText)) return; IXmlElement attributionTextElement = CreateElement(xmldoc, "text"); IXmlNode bindingNode = GetNode(xmldoc, "binding"); IXmlNode appendedChild = AppendNode(bindingNode, (IXmlNode)attributionTextElement); SetAttribute(appendedChild, "placement", "attribution"); SetNodeValueString(infoGeneric.AttributionText, xmldoc, appendedChild); } static void UpdateDisplayTimestamp(IXmlDocument xmldoc, IPredefinedToastNotificationInfo info) { IPredefinedToastNotificationInfoGeneric infoGeneric = info as IPredefinedToastNotificationInfoGeneric; if(infoGeneric.DisplayTimestamp == null) return; IXmlNode toastNode = GetNode(xmldoc, "toast"); string displayTimestamp = infoGeneric.DisplayTimestamp.Value.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"); SetAttribute(toastNode, "displayTimestamp", displayTimestamp); } static void UpdateInlineImage(IPredefinedToastNotificationInfo info, IXmlDocument content) { if(!string.IsNullOrEmpty(info.ImagePath)) { string imagePath = new System.Uri(info.ImagePath).AbsoluteUri; if(info.ToastTemplateType == ToastTemplateType.ToastGeneric) CreateInlineImageNode(content, imagePath); else SetImageSrc(content, imagePath); } } static void UpdateAppLogoImage(IPredefinedToastNotificationInfo info, IXmlDocument content) { IPredefinedToastNotificationInfoGeneric infoGeneric = info as IPredefinedToastNotificationInfoGeneric; if(!string.IsNullOrEmpty(infoGeneric.AppLogoImagePath) && info.ToastTemplateType == ToastTemplateType.ToastGeneric) { string appLogoImagePath = new System.Uri(infoGeneric.AppLogoImagePath).AbsoluteUri; IXmlNode appLogoImageNode = CreateInlineImageNode(content, appLogoImagePath); SetAttribute(appLogoImageNode, "placement", "appLogoOverride"); if(infoGeneric.AppLogoImageCrop == ImageCropType.Circle) SetAttribute(appLogoImageNode, "hint-crop", "circle"); } } static void UpdateHeroImage(IPredefinedToastNotificationInfo info, IXmlDocument content) { IPredefinedToastNotificationInfoGeneric infoGeneric = info as IPredefinedToastNotificationInfoGeneric; if(!string.IsNullOrEmpty(infoGeneric.HeroImagePath) && info.ToastTemplateType == ToastTemplateType.ToastGeneric) { string heroImagePath = new System.Uri(infoGeneric.HeroImagePath).AbsoluteUri; IXmlNode heroImageNode = CreateInlineImageNode(content, heroImagePath); SetAttribute(heroImageNode, "placement", "hero"); } } static IXmlNode CreateInlineImageNode(IXmlDocument content, string imagePath) { IXmlNode bindingNode = GetNode(content, "binding"); IXmlElement imageElement = CreateElement(content, "image"); IXmlNode inlineImageNode = AppendNode(bindingNode, (IXmlNode)imageElement); SetAttribute(inlineImageNode, "src", imagePath); return inlineImageNode; } static void UpdateSound(IXmlDocument content, IPredefinedToastNotificationInfo info) { if(info.Sound != PredefinedSound.Notification_Default) SetSound(content, info.Sound); } static void UpdateDuration(IXmlDocument xmldoc, IPredefinedToastNotificationInfo info) { NotificationDuration duration = info.Duration; if(IsLoopingSound(info.Sound)) duration = NotificationDuration.Long; if(duration != NotificationDuration.Default) SetAttribute(xmldoc, "toast", "duration", "long"); } static void SetAttribute(IXmlDocument xmldoc, string tagName, string attributeName, string attributeValue) { IXmlNode node = GetNode(xmldoc, tagName); SetAttribute(node, attributeName, attributeValue); } static void SetAttribute(IXmlNode node, string attributeName, string attributeValue) { SetAttribute((IXmlElement)node, attributeName, attributeValue); } static void SetAttribute(IXmlElement node, string attributeName, string attributeValue) { using(var hString_attributeName = HSTRING.FromString(attributeName)) using(var hString_attributeValue = HSTRING.FromString(attributeValue)) ComFunctions.CheckHRESULT(node.SetAttribute(hString_attributeName, hString_attributeValue)); } static void SetSound(IXmlDocument xmldoc, PredefinedSound sound) { string soundXml = "ms-winsoundevent:" + sound.ToString().Replace("_", "."); IXmlElement soundElement = CreateElement(xmldoc, "audio"); if(sound == PredefinedSound.NoSound) { SetAttribute(soundElement, "silent", "true"); } else { SetAttribute(soundElement, "src", soundXml); SetAttribute(soundElement, "loop", IsLoopingSound(sound).ToString().ToLower()); } IXmlNode toastNode = GetNode(xmldoc, "toast"); AppendNode(toastNode, (IXmlNode)soundElement); } static IXmlNode GetNode(IXmlDocument xmldoc, string tagName) { IXmlNodeList nodes = GetNodes(xmldoc, tagName); IXmlNode node = GetNode(nodes, 0); return node; } static IXmlNode GetNode(IXmlNodeList nodes, uint index) { IXmlNode node; ComFunctions.CheckHRESULT(nodes.Item(index, out node)); return node; } static IXmlNodeList GetNodes(IXmlDocument xmldoc, string tagName) { IXmlNodeList nodes; using(var hStrign_tagName = HSTRING.FromString(tagName)) ComFunctions.CheckHRESULT(xmldoc.GetElementsByTagName(hStrign_tagName, out nodes)); return nodes; } static IXmlElement CreateElement(IXmlDocument xmldoc, string elementName) { IXmlElement element; using(var hStrign_elementName = HSTRING.FromString(elementName)) ComFunctions.CheckHRESULT(xmldoc.CreateElement(hStrign_elementName, out element)); return element; } static IXmlNode AppendNode(IXmlNode parentNode, IXmlNode childNode) { IXmlNode appendedChild; ComFunctions.CheckHRESULT(parentNode.AppendChild(childNode, out appendedChild)); return appendedChild; } public bool IsAssigned { get; set; } void RemoveTempFile(string filePath) { if(string.IsNullOrEmpty(filePath)) return; try { if(File.Exists(filePath)) File.Delete(filePath); } catch { } } } }
// 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.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal interface ICodeModelService : ICodeModelNavigationPointService { /// <summary> /// Retrieves the Option nodes (i.e. VB Option statements) parented /// by the given node. /// </summary> IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent); /// <summary> /// Retrieves the import nodes (e.g. using/Import directives) parented /// by the given node. /// </summary> IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent); /// <summary> /// Retrieves the attributes parented or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent); /// <summary> /// Retrieves the attribute arguments parented by the given node. /// </summary> IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent); /// <summary> /// Retrieves the Inherits nodes (i.e. VB Inherits statements) parented /// or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent); /// <summary> /// Retrieves the Implements nodes (i.e. VB Implements statements) parented /// or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent); /// <summary> /// Retrieves the logical members of a given node, flattening the declarators /// in field declarations. For example, if a class contains the field "int foo, bar", /// two nodes are returned -- one for "foo" and one for "bar". /// </summary> IEnumerable<SyntaxNode> GetFlattenedMemberNodes(SyntaxNode parent); SyntaxNodeKey GetNodeKey(SyntaxNode node); SyntaxNodeKey TryGetNodeKey(SyntaxNode node); SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree); bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node); bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope); string Language { get; } string AssemblyAttributeString { get; } EnvDTE.CodeElement CreateInternalCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol); EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel); EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol); /// <summary> /// Used by RootCodeModel.CreateCodeTypeRef to create an EnvDTE.CodeTypeRef. /// </summary> EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type); EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol); string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol); string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol); bool IsParameterNode(SyntaxNode node); bool IsAttributeNode(SyntaxNode node); bool IsAttributeArgumentNode(SyntaxNode node); bool IsOptionNode(SyntaxNode node); bool IsImportNode(SyntaxNode node); ISymbol ResolveSymbol(Workspace workspace, ProjectId projectId, SymbolKey symbolId); string GetUnescapedName(string name); /// <summary> /// Retrieves the value to be returned from the EnvDTE.CodeElement.Name property. /// </summary> string GetName(SyntaxNode node); SyntaxNode GetNodeWithName(SyntaxNode node); SyntaxNode SetName(SyntaxNode node, string name); /// <summary> /// Retrieves the value to be returned from the EnvDTE.CodeElement.FullName property. /// </summary> string GetFullName(SyntaxNode node, SemanticModel semanticModel); /// <summary> /// Retrieves the value to be returned from the EnvDTE.CodeElement.FullName property for external code elements /// </summary> string GetFullName(ISymbol symbol); /// <summary> /// Given a name, attempts to convert it to a fully qualified name. /// </summary> string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel); void Rename(ISymbol symbol, string newName, Solution solution); SyntaxNode GetNodeWithModifiers(SyntaxNode node); SyntaxNode GetNodeWithType(SyntaxNode node); SyntaxNode GetNodeWithInitializer(SyntaxNode node); EnvDTE.vsCMAccess GetAccess(ISymbol symbol); EnvDTE.vsCMAccess GetAccess(SyntaxNode node); SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access); EnvDTE.vsCMElement GetElementKind(SyntaxNode node); bool IsAccessorNode(SyntaxNode node); MethodKind GetAccessorKind(SyntaxNode node); bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode); bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode); bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode); bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode); bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode); bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode); bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode); bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode); void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal); void GetInheritsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode inheritsNode, out string namespaceName, out int ordinal); void GetImplementsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode implementsNode, out string namespaceName, out int ordinal); void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index); void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal); SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode); string GetAttributeTarget(SyntaxNode attributeNode); string GetAttributeValue(SyntaxNode attributeNode); SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value); SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value); /// <summary> /// Given a node, finds the related node that holds on to the attribute information. /// Generally, this will be an ancestor node. For example, given a C# VariableDeclarator, /// looks up the syntax tree to find the FieldDeclaration. /// </summary> SyntaxNode GetNodeWithAttributes(SyntaxNode node); /// <summary> /// Given node for an attribute, returns a node that can represent the parent. /// For example, an attribute on a C# field cannot use the FieldDeclaration (as it is /// not keyed) but instead must use one of the FieldDeclaration's VariableDeclarators. /// </summary> SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node); SyntaxNode CreateAttributeNode(string name, string value, string target = null); SyntaxNode CreateAttributeArgumentNode(string name, string value); SyntaxNode CreateImportNode(string name, string alias = null); SyntaxNode CreateParameterNode(string name, string type); string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode); string GetImportAlias(SyntaxNode node); string GetImportNamespaceOrType(SyntaxNode node); string GetParameterName(SyntaxNode node); string GetParameterFullName(SyntaxNode node); EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node); SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind); IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent); EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name); bool SupportsEventThrower { get; } bool GetCanOverride(SyntaxNode memberNode); SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value); EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind); string GetComment(SyntaxNode node); SyntaxNode SetComment(SyntaxNode node, string value); EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode); SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind); EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol); SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind); string GetDocComment(SyntaxNode node); SyntaxNode SetDocComment(SyntaxNode node, string value); EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol); EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); SyntaxNode SetInheritanceKind(SyntaxNode node, EnvDTE80.vsCMInheritanceKind kind); bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol); SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value); bool GetIsConstant(SyntaxNode memberNode); SyntaxNode SetIsConstant(SyntaxNode memberNode, bool value); bool GetIsDefault(SyntaxNode propertyNode); SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value); bool GetIsGeneric(SyntaxNode memberNode); bool GetIsPropertyStyleEvent(SyntaxNode eventNode); bool GetIsShared(SyntaxNode memberNode, ISymbol symbol); SyntaxNode SetIsShared(SyntaxNode memberNode, bool value); bool GetMustImplement(SyntaxNode memberNode); SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value); EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode); SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind); EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode); SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol); Document Delete(Document document, SyntaxNode node); string GetMethodXml(SyntaxNode node, SemanticModel semanticModel); string GetInitExpression(SyntaxNode node); SyntaxNode AddInitExpression(SyntaxNode node, string value); CodeGenerationDestination GetDestination(SyntaxNode containerNode); /// <summary> /// Retrieves the Accessibility for an EnvDTE.vsCMAccess. If the specified value is /// EnvDTE.vsCMAccess.vsCMAccessDefault, then the SymbolKind and CodeGenerationDestination hints /// will be used to retrieve the correct Accessibility for the current language. /// </summary> Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified); bool GetWithEvents(EnvDTE.vsCMAccess access); /// <summary> /// Given an "type" argument received from a CodeModel client, converts it to an ITypeSymbol. Note that /// this parameter is a VARIANT and could be an EnvDTE.vsCMTypeRef, a string representing a fully-qualified /// type name, or an EnvDTE.CodeTypeRef. /// </summary> ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position); ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation); SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type); int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); SyntaxNode InsertAttribute( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertAttributeArgument( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeArgumentNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertImport( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode importNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertMember( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode newMemberNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertParameter( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode parameterNode, CancellationToken cancellationToken, out Document newDocument); Document UpdateNode( Document document, SyntaxNode node, SyntaxNode newNode, CancellationToken cancellationToken); Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree); bool IsNamespace(SyntaxNode node); bool IsType(SyntaxNode node); IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel); bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel); Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken); Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken); string[] GetFunctionExtenderNames(); object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol); string[] GetPropertyExtenderNames(); object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol); string[] GetExternalTypeExtenderNames(); object GetExternalTypeExtender(string name, string externalLocation); string[] GetTypeExtenderNames(); object GetTypeExtender(string name, AbstractCodeType codeType); bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol); SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol); SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags); void AttachFormatTrackingToBuffer(ITextBuffer buffer); void DetachFormatTrackingToBuffer(ITextBuffer buffer); void EnsureBufferFormatted(ITextBuffer buffer); } }
// 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="CurrencyConstantServiceClient"/> instances.</summary> public sealed partial class CurrencyConstantServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="CurrencyConstantServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="CurrencyConstantServiceSettings"/>.</returns> public static CurrencyConstantServiceSettings GetDefault() => new CurrencyConstantServiceSettings(); /// <summary> /// Constructs a new <see cref="CurrencyConstantServiceSettings"/> object with default settings. /// </summary> public CurrencyConstantServiceSettings() { } private CurrencyConstantServiceSettings(CurrencyConstantServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetCurrencyConstantSettings = existing.GetCurrencyConstantSettings; OnCopy(existing); } partial void OnCopy(CurrencyConstantServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CurrencyConstantServiceClient.GetCurrencyConstant</c> and /// <c>CurrencyConstantServiceClient.GetCurrencyConstantAsync</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 GetCurrencyConstantSettings { 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="CurrencyConstantServiceSettings"/> object.</returns> public CurrencyConstantServiceSettings Clone() => new CurrencyConstantServiceSettings(this); } /// <summary> /// Builder class for <see cref="CurrencyConstantServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class CurrencyConstantServiceClientBuilder : gaxgrpc::ClientBuilderBase<CurrencyConstantServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public CurrencyConstantServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public CurrencyConstantServiceClientBuilder() { UseJwtAccessWithScopes = CurrencyConstantServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref CurrencyConstantServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CurrencyConstantServiceClient> task); /// <summary>Builds the resulting client.</summary> public override CurrencyConstantServiceClient Build() { CurrencyConstantServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<CurrencyConstantServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<CurrencyConstantServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private CurrencyConstantServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return CurrencyConstantServiceClient.Create(callInvoker, Settings); } private async stt::Task<CurrencyConstantServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return CurrencyConstantServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => CurrencyConstantServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => CurrencyConstantServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => CurrencyConstantServiceClient.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>CurrencyConstantService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch currency constants. /// </remarks> public abstract partial class CurrencyConstantServiceClient { /// <summary> /// The default endpoint for the CurrencyConstantService 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 CurrencyConstantService scopes.</summary> /// <remarks> /// The default CurrencyConstantService 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="CurrencyConstantServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="CurrencyConstantServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="CurrencyConstantServiceClient"/>.</returns> public static stt::Task<CurrencyConstantServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new CurrencyConstantServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="CurrencyConstantServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="CurrencyConstantServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="CurrencyConstantServiceClient"/>.</returns> public static CurrencyConstantServiceClient Create() => new CurrencyConstantServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="CurrencyConstantServiceClient"/> 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="CurrencyConstantServiceSettings"/>.</param> /// <returns>The created <see cref="CurrencyConstantServiceClient"/>.</returns> internal static CurrencyConstantServiceClient Create(grpccore::CallInvoker callInvoker, CurrencyConstantServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } CurrencyConstantService.CurrencyConstantServiceClient grpcClient = new CurrencyConstantService.CurrencyConstantServiceClient(callInvoker); return new CurrencyConstantServiceClientImpl(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 CurrencyConstantService client</summary> public virtual CurrencyConstantService.CurrencyConstantServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested currency constant. /// /// 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::CurrencyConstant GetCurrencyConstant(GetCurrencyConstantRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested currency constant. /// /// 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::CurrencyConstant> GetCurrencyConstantAsync(GetCurrencyConstantRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested currency constant. /// /// 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::CurrencyConstant> GetCurrencyConstantAsync(GetCurrencyConstantRequest request, st::CancellationToken cancellationToken) => GetCurrencyConstantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested currency constant. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. Resource name of the currency constant to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CurrencyConstant GetCurrencyConstant(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetCurrencyConstant(new GetCurrencyConstantRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested currency constant. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. Resource name of the currency constant 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::CurrencyConstant> GetCurrencyConstantAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetCurrencyConstantAsync(new GetCurrencyConstantRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested currency constant. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. Resource name of the currency constant 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::CurrencyConstant> GetCurrencyConstantAsync(string resourceName, st::CancellationToken cancellationToken) => GetCurrencyConstantAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested currency constant. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. Resource name of the currency constant to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CurrencyConstant GetCurrencyConstant(gagvr::CurrencyConstantName resourceName, gaxgrpc::CallSettings callSettings = null) => GetCurrencyConstant(new GetCurrencyConstantRequest { ResourceNameAsCurrencyConstantName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested currency constant. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. Resource name of the currency constant 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::CurrencyConstant> GetCurrencyConstantAsync(gagvr::CurrencyConstantName resourceName, gaxgrpc::CallSettings callSettings = null) => GetCurrencyConstantAsync(new GetCurrencyConstantRequest { ResourceNameAsCurrencyConstantName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested currency constant. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. Resource name of the currency constant 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::CurrencyConstant> GetCurrencyConstantAsync(gagvr::CurrencyConstantName resourceName, st::CancellationToken cancellationToken) => GetCurrencyConstantAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>CurrencyConstantService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch currency constants. /// </remarks> public sealed partial class CurrencyConstantServiceClientImpl : CurrencyConstantServiceClient { private readonly gaxgrpc::ApiCall<GetCurrencyConstantRequest, gagvr::CurrencyConstant> _callGetCurrencyConstant; /// <summary> /// Constructs a client wrapper for the CurrencyConstantService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="CurrencyConstantServiceSettings"/> used within this client. /// </param> public CurrencyConstantServiceClientImpl(CurrencyConstantService.CurrencyConstantServiceClient grpcClient, CurrencyConstantServiceSettings settings) { GrpcClient = grpcClient; CurrencyConstantServiceSettings effectiveSettings = settings ?? CurrencyConstantServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetCurrencyConstant = clientHelper.BuildApiCall<GetCurrencyConstantRequest, gagvr::CurrencyConstant>(grpcClient.GetCurrencyConstantAsync, grpcClient.GetCurrencyConstant, effectiveSettings.GetCurrencyConstantSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetCurrencyConstant); Modify_GetCurrencyConstantApiCall(ref _callGetCurrencyConstant); 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_GetCurrencyConstantApiCall(ref gaxgrpc::ApiCall<GetCurrencyConstantRequest, gagvr::CurrencyConstant> call); partial void OnConstruction(CurrencyConstantService.CurrencyConstantServiceClient grpcClient, CurrencyConstantServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC CurrencyConstantService client</summary> public override CurrencyConstantService.CurrencyConstantServiceClient GrpcClient { get; } partial void Modify_GetCurrencyConstantRequest(ref GetCurrencyConstantRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested currency constant. /// /// 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::CurrencyConstant GetCurrencyConstant(GetCurrencyConstantRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetCurrencyConstantRequest(ref request, ref callSettings); return _callGetCurrencyConstant.Sync(request, callSettings); } /// <summary> /// Returns the requested currency constant. /// /// 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::CurrencyConstant> GetCurrencyConstantAsync(GetCurrencyConstantRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetCurrencyConstantRequest(ref request, ref callSettings); return _callGetCurrencyConstant.Async(request, callSettings); } } }
//----------------------------------------------------------------------- // <copyright> // Copyright (C) Ruslan Yakushev for the PHP Manager for IIS project. // // This file is subject to the terms and conditions of the Microsoft Public License (MS-PL). // See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL for more details. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Windows.Forms; using Microsoft.Web.Management.Client; using Microsoft.Web.Management.Client.Win32; using Web.Management.PHP.Config; namespace Web.Management.PHP.Extensions { [ModulePageIdentifier(Globals.PHPExtensionsPageIdentifier)] internal sealed class AllExtensionsPage : ModuleListPage, IModuleChildPage { private ColumnHeader _nameColumn; private ColumnHeader _stateColumn; private ModuleListPageGrouping _stateGrouping; private PageTaskList _taskList; private ModuleListPageSearchField[] _searchFields; private PHPIniFile _file; private const string NameString = "Name"; private const string StateString = "State"; private string _filterBy; private string _filterValue; private IModulePage _parentPage; private string _updatedExtensionName; protected override bool CanRefresh { get { return true; } } protected override bool CanSearch { get { return true; } } protected override ModuleListPageGrouping DefaultGrouping { get { return Groupings[0]; } } public override ModuleListPageGrouping[] Groupings { get { if (_stateGrouping == null) { _stateGrouping = new ModuleListPageGrouping(StateString, Resources.AllExtensionsPageStateField); } return new ModuleListPageGrouping[] { _stateGrouping }; } } internal bool IsReadOnly { get { return Connection.ConfigurationPath.PathType == Microsoft.Web.Management.Server.ConfigurationPathType.Site && !Connection.IsUserServerAdministrator; } } private new PHPModule Module { get { return (PHPModule)base.Module; } } public IModulePage ParentPage { get { return _parentPage; } set { _parentPage = value; } } protected override ModuleListPageSearchField[] SearchFields { get { if (_searchFields == null) { _searchFields = new ModuleListPageSearchField[]{ new ModuleListPageSearchField(NameString, Resources.AllSettingsPageNameField)}; } return _searchFields; } } private PHPExtensionItem SelectedItem { get { if (ListView.SelectedIndices.Count == 1) { return ListView.SelectedItems[0] as PHPExtensionItem; } return null; } } protected override TaskListCollection Tasks { get { TaskListCollection tasks = base.Tasks; if (_taskList == null) { _taskList = new PageTaskList(this); } tasks.Add(_taskList); return tasks; } } internal void AddExtension() { using (AddExtensionDialog dlg = new AddExtensionDialog(this.Module, Connection.IsLocalConnection)) { if (ShowDialog(dlg) == DialogResult.OK) { _updatedExtensionName = dlg.AddedExtensionName; Refresh(); } } } private void GetExtensions() { StartAsyncTask(Resources.AllExtensionsPageGettingExtensions, OnGetExtensions, OnGetExtensionsCompleted); } protected override ListViewGroup[] GetGroups(ModuleListPageGrouping grouping) { ListViewGroup[] result = new ListViewGroup[2]; result[0] = new ListViewGroup(Resources.AllExtensionsPageEnabledGroup, Resources.AllExtensionsPageEnabledGroup); result[1] = new ListViewGroup(Resources.AllExtensionsPageDisabledGroup, Resources.AllExtensionsPageDisabledGroup); return result; } private void GoBack() { Navigate(typeof(PHPPage)); } protected override void Initialize(object navigationData) { base.Initialize(navigationData); if (navigationData != null) { _updatedExtensionName = navigationData as string; } } protected override void InitializeListPage() { _nameColumn = new ColumnHeader(); _nameColumn.Text = Resources.AllExtensionsPageNameField; _nameColumn.Width = 160; _stateColumn = new ColumnHeader(); _stateColumn.Text = Resources.AllExtensionsPageStateField; _stateColumn.Width = 60; ListView.Columns.AddRange(new ColumnHeader[] { _nameColumn, _stateColumn }); ListView.MultiSelect = false; ListView.SelectedIndexChanged += new EventHandler(OnListViewSelectedIndexChanged); } private void LoadExtensions(PHPIniFile file) { try { ListView.SuspendLayout(); ListView.Items.Clear(); foreach (PHPIniExtension extension in file.Extensions) { if (_filterBy != null && _filterValue != null) { if (_filterBy == NameString && extension.Name.IndexOf(_filterValue, StringComparison.OrdinalIgnoreCase) == -1) { continue; } } ListView.Items.Add(new PHPExtensionItem(extension)); } if (SelectedGrouping != null) { Group(SelectedGrouping); } } finally { ListView.ResumeLayout(); } } protected override void OnActivated(bool initialActivation) { base.OnActivated(initialActivation); if (initialActivation) { GetExtensions(); } } private void OnGetExtensions(object sender, DoWorkEventArgs e) { e.Result = Module.Proxy.GetPHPIniSettings(); } private void OnGetExtensionsCompleted(object sender, RunWorkerCompletedEventArgs e) { try { object o = e.Result; _file = new PHPIniFile(); _file.SetData(o); LoadExtensions(_file); // If name of the updated extension was saved then use it to re-select it. if (!String.IsNullOrEmpty(_updatedExtensionName)) { SelectExtensionByName(_updatedExtensionName); _updatedExtensionName = null; } } catch (Exception ex) { DisplayErrorMessage(ex, Resources.ResourceManager); } } protected override void OnGroup(ModuleListPageGrouping grouping) { ListView.SuspendLayout(); try { foreach (PHPExtensionItem item in ListView.Items) { if (grouping == _stateGrouping) { item.Group = ListView.Groups[item.State]; } } } finally { ListView.ResumeLayout(); } } private void OnListViewSelectedIndexChanged(object sender, EventArgs e) { Update(); } protected override void OnSearch(ModuleListPageSearchOptions options) { if (options.ShowAll) { _filterBy = null; _filterValue = null; LoadExtensions(_file); } else { _filterBy = options.Field.Name; _filterValue = options.Text; LoadExtensions(_file); } } internal void OpenPHPIniFile() { try { string physicalPath = Module.Proxy.GetPHPIniPhysicalPath(); if (!String.IsNullOrEmpty(physicalPath) && String.Equals(Path.GetExtension(physicalPath), ".ini", StringComparison.OrdinalIgnoreCase) && File.Exists(physicalPath)) { Process.Start(physicalPath); } else { ShowMessage(String.Format(CultureInfo.CurrentCulture, Resources.ErrorFileDoesNotExist, physicalPath), MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { DisplayErrorMessage(ex, Resources.ResourceManager); } } protected override void Refresh() { GetExtensions(); } // Used to select an item by name after refresh private void SelectExtensionByName(string name) { foreach (PHPExtensionItem item in ListView.Items) { if (String.Equals(item.Extension.Name, name, StringComparison.OrdinalIgnoreCase)) { item.Selected = true; item.EnsureVisible(); break; } } } private void SetExtensionState(bool enabled) { PHPExtensionItem item = SelectedItem; Debug.Assert(item != null); item.Extension.Enabled = enabled; RemoteObjectCollection<PHPIniExtension> extensions = new RemoteObjectCollection<PHPIniExtension>(); extensions.Add(item.Extension); try { Module.Proxy.UpdateExtensions(extensions); // Save the name of the updated extension so that we can select it after refresh _updatedExtensionName = item.Extension.Name; Refresh(); } catch (Exception ex) { DisplayErrorMessage(ex, Resources.ResourceManager); } } protected override bool ShowHelp() { return ShowOnlineHelp(); } protected override bool ShowOnlineHelp() { return Helper.Browse(Globals.AllExtensionsOnlineHelp); } private class PageTaskList : TaskList { private AllExtensionsPage _page; public PageTaskList(AllExtensionsPage page) { _page = page; } public void AddExtension() { _page.AddExtension(); } public void DisableExtension() { _page.SetExtensionState(false); } public void EnableExtension() { _page.SetExtensionState(true); } public override System.Collections.ICollection GetTaskItems() { List<TaskItem> tasks = new List<TaskItem>(); if (_page.IsReadOnly) { tasks.Add(new MessageTaskItem(MessageTaskItemType.Information, Resources.AllPagesPageIsReadOnly, "Information")); } else { tasks.Add(new MethodTaskItem("AddExtension", Resources.AllPagesAddTask, "Edit", null)); if (_page.SelectedItem != null) { if (_page.SelectedItem.Extension.Enabled) { tasks.Add(new MethodTaskItem("DisableExtension", Resources.AllExtensionsPageDisableTask, "Edit", null)); } else { tasks.Add(new MethodTaskItem("EnableExtension", Resources.AllExtensionsPageEnableTask, "Edit", null)); } } if (_page.Connection.IsLocalConnection) { tasks.Add(new MethodTaskItem("OpenPHPIniFile", Resources.AllPagesOpenPHPIniTask, "Tasks", null)); } } tasks.Add(new MethodTaskItem("GoBack", Resources.AllPagesGoBackTask, "Tasks", null, Resources.GoBack16)); return tasks; } public void GoBack() { _page.GoBack(); } public void OpenPHPIniFile() { _page.OpenPHPIniFile(); } } private class PHPExtensionItem : ListViewItem { private PHPIniExtension _extension; public PHPExtensionItem(PHPIniExtension extension) { _extension = extension; Text = _extension.Name; SubItems.Add(this.State); if (!extension.Enabled) { this.ForeColor = SystemColors.ControlDark; } } public PHPIniExtension Extension { get { return _extension; } } public string State { get { return _extension.Enabled ? Resources.AllExtensionsPageEnabledGroup : Resources.AllExtensionsPageDisabledGroup; } } } } }
/* * Exchange Web Services Managed API * * 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. */ namespace Microsoft.Exchange.WebServices.Data { using System.Collections.Generic; /// <summary> /// Represents a ResolveNames request. /// </summary> internal sealed class ResolveNamesRequest : MultiResponseServiceRequest<ResolveNamesResponse> { private static LazyMember<Dictionary<ResolveNameSearchLocation, string>> searchScopeMap = new LazyMember<Dictionary<ResolveNameSearchLocation, string>>( delegate { Dictionary<ResolveNameSearchLocation, string> map = new Dictionary<ResolveNameSearchLocation, string>(); map.Add(ResolveNameSearchLocation.DirectoryOnly, "ActiveDirectory"); map.Add(ResolveNameSearchLocation.DirectoryThenContacts, "ActiveDirectoryContacts"); map.Add(ResolveNameSearchLocation.ContactsOnly, "Contacts"); map.Add(ResolveNameSearchLocation.ContactsThenDirectory, "ContactsActiveDirectory"); return map; }); private string nameToResolve; private bool returnFullContactData; private ResolveNameSearchLocation searchLocation; private PropertySet contactDataPropertySet; private FolderIdWrapperList parentFolderIds = new FolderIdWrapperList(); /// <summary> /// Asserts the valid. /// </summary> internal override void Validate() { base.Validate(); EwsUtilities.ValidateNonBlankStringParam(this.NameToResolve, "NameToResolve"); } /// <summary> /// Creates the service response. /// </summary> /// <param name="service">The service.</param> /// <param name="responseIndex">Index of the response.</param> /// <returns>Service response.</returns> internal override ResolveNamesResponse CreateServiceResponse(ExchangeService service, int responseIndex) { return new ResolveNamesResponse(service); } /// <summary> /// Gets the name of the XML element. /// </summary> /// <returns>XML element name,</returns> internal override string GetXmlElementName() { return XmlElementNames.ResolveNames; } /// <summary> /// Gets the name of the response XML element. /// </summary> /// <returns>XML element name,</returns> internal override string GetResponseXmlElementName() { return XmlElementNames.ResolveNamesResponse; } /// <summary> /// Gets the name of the response message XML element. /// </summary> /// <returns>XML element name,</returns> internal override string GetResponseMessageXmlElementName() { return XmlElementNames.ResolveNamesResponseMessage; } /// <summary> /// Initializes a new instance of the <see cref="ResolveNamesRequest"/> class. /// </summary> /// <param name="service">The service.</param> internal ResolveNamesRequest(ExchangeService service) : base(service, ServiceErrorHandling.ThrowOnError) { } /// <summary> /// Gets the expected response message count. /// </summary> /// <returns>Number of expected response messages.</returns> internal override int GetExpectedResponseMessageCount() { return 1; } /// <summary> /// Writes the attributes to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteAttributesToXml(EwsServiceXmlWriter writer) { writer.WriteAttributeValue( XmlAttributeNames.ReturnFullContactData, this.ReturnFullContactData); string searchScope = null; searchScopeMap.Member.TryGetValue(this.SearchLocation, out searchScope); EwsUtilities.Assert( !string.IsNullOrEmpty(searchScope), "ResolveNameRequest.WriteAttributesToXml", "The specified search location cannot be mapped to an EWS search scope."); string propertySet = null; if (this.contactDataPropertySet != null) { PropertySet.DefaultPropertySetMap.Member.TryGetValue(this.contactDataPropertySet.BasePropertySet, out propertySet); } if (!this.Service.Exchange2007CompatibilityMode) { writer.WriteAttributeValue(XmlAttributeNames.SearchScope, searchScope); } if (!string.IsNullOrEmpty(propertySet)) { writer.WriteAttributeValue(XmlAttributeNames.ContactDataShape, propertySet); } } /// <summary> /// Writes the elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { this.ParentFolderIds.WriteToXml( writer, XmlNamespace.Messages, XmlElementNames.ParentFolderIds); writer.WriteElementValue( XmlNamespace.Messages, XmlElementNames.UnresolvedEntry, this.NameToResolve); } /// <summary> /// Gets the request version. /// </summary> /// <returns>Earliest Exchange version in which this request is supported.</returns> internal override ExchangeVersion GetMinimumRequiredServerVersion() { return ExchangeVersion.Exchange2007_SP1; } /// <summary> /// Gets or sets the name to resolve. /// </summary> /// <value>The name to resolve.</value> public string NameToResolve { get { return this.nameToResolve; } set { this.nameToResolve = value; } } /// <summary> /// Gets or sets a value indicating whether to return full contact data or not. /// </summary> /// <value> /// <c>true</c> if should return full contact data; otherwise, <c>false</c>. /// </value> public bool ReturnFullContactData { get { return this.returnFullContactData; } set { this.returnFullContactData = value; } } /// <summary> /// Gets or sets the search location. /// </summary> /// <value>The search scope.</value> public ResolveNameSearchLocation SearchLocation { get { return this.searchLocation; } set { this.searchLocation = value; } } /// <summary> /// Gets or sets the PropertySet for Contact Data /// </summary> /// <value>The PropertySet</value> public PropertySet ContactDataPropertySet { get { return this.contactDataPropertySet; } set { this.contactDataPropertySet = value; } } /// <summary> /// Gets the parent folder ids. /// </summary> /// <value>The parent folder ids.</value> public FolderIdWrapperList ParentFolderIds { get { return this.parentFolderIds; } } } }
/* * Copyright 2005 OpenXRI Foundation * Subsequently ported and altered by Andrew Arnott * * 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 DotNetXri.Client.Tools { using System.Text; using java.net.URL; using java.net.URLConnection; using java.util.Iterator; using org.openxri.XRI; using org.openxri.resolve.ResolveChain; using org.openxri.resolve.ResolveInfo; using org.openxri.resolve.Resolver; using org.openxri.resolve.TrustType; using org.openxri.resolve.exception.XRIResolutionException; using org.openxri.xml.Service; using org.openxri.xml.Tags; using org.openxri.xml.XRD; using org.openxri.xml.XRDS; /* ******************************************************************************** * Class: XRITraceRt ******************************************************************************** */ /** * Provides tracert-like output for XRI resolution. * See outputUsage for command line usage and program output. * * @author =steven.churchill (ooTao.com) */ public class XRITraceRt { // program results private const int SUCCESS = 0; private const int FAILURE = 1; // program commands as command line args private const String CMD_HELP = "help"; // options as command line args private const String OPT_ROOT_EQUALS_URI = "-root_equals_auth"; private const String OPT_ROOT_AT_URI = "-root_at_auth"; private const String OPT_VERBOSE = "-verbose"; private const String OPT_NO_HEADER = "-no_header"; private const String ROOT_DEF_URI = "http://localhost:8080/xri/resolve?ns=at"; // data argument variable private String msTargetXRI; // option variables private bool mbIsVerbose; private bool mbDontOutputHeader; private String msRootEqualsURI; private String msRootAtURI; /* **************************************************************************** * main() **************************************************************************** */ /** * Invokes the process routine to execute the command specified by * the given arguments. See outputUsage for details about program * arguments and output. */ public static void main(String[] oArgs) { StringBuilder sOutput = new StringBuilder(); XRITraceRt oTraceRt = new XRITraceRt(); int iResult = oTraceRt.process(sOutput, oArgs); exit(sOutput, iResult); } // main() /* **************************************************************************** * process() **************************************************************************** */ /** * Executes the xritracert command as indicated by the input args. See * outputUsage for the forms of invocation and details about the program * arguments. * * @param sArgs - command line arguments (e.g., from main) * @param sOutput - program output (e.g., for stdout) * * @return SUCCESS or FAILURE */ public int process(StringBuilder sOutput, String[] sArgs) { try { // re-initialize variables so this may be called more than once sOutput.setLength(0); msTargetXRI = null; mbIsVerbose = false; mbDontOutputHeader = false; msRootEqualsURI = ROOT_DEF_URI; msRootAtURI = ROOT_DEF_URI; // exit with message if no arguments passed on the command line if (sArgs.length == 0) { outputPleaseTypeHelp(sOutput); return FAILURE; } // this is the "help" form of invocation (usage 2) if (sArgs[0].equalsIgnoreCase(CMD_HELP)) { outputUsage(sOutput); return SUCCESS; } // from here on, we're dealing with the "normal" form of invocation // (usage 1). // scan the args, setting member variables for options, rootURI, // and resolve XRI int iResult = scanArgs(sOutput, sArgs); if (iResult == FAILURE) { return FAILURE; } // validate that the root uris are ok iResult = validateRootURIs(sOutput); if (iResult == FAILURE) { return FAILURE; } // create and configure a resolver Resolver resolver = new Resolver(); XRD eqRoot = new XRD(); Service eqAuthService = new Service(); eqAuthService.addMediaType(Tags.CONTENT_TYPE_XRDS + ";trust=none"); eqAuthService.addType(Tags.SERVICE_AUTH_RES); eqAuthService.addURI(msRootEqualsURI); eqRoot.addService(eqAuthService); XRD atRoot = new XRD(); Service atAuthService = new Service(); atAuthService.addMediaType(Tags.CONTENT_TYPE_XRDS + ";trust=none"); atAuthService.addType(Tags.SERVICE_AUTH_RES); atAuthService.addURI(msRootAtURI); atRoot.addService(atAuthService); resolver.setAuthority("=", eqRoot); resolver.setAuthority("@", atRoot); // invoke the tracert tracert(sOutput, resolver); } catch (Throwable oThrowable) { outputException(sOutput, oThrowable); return FAILURE; } return SUCCESS; } /* **************************************************************************** * tracert() **************************************************************************** */ /** * For the XRI specified msTargetXRI, outputs the URIs for the registry * servers used at each step of the resolution as per the command-line * options. * @param sOutput - string buffer for output * @param resolver - resolver for top-most at/equals authority * * @return SUCCESS or FAILURE */ private void tracert( StringBuilder sOutput, Resolver resolver) throws XRIResolutionException { // TODO: trusted resolution is currently not supported TrustType trustType = new TrustType(TrustType.TRUST_NONE); bool followRefs = true; // note: See also Resolver.resolve // resolver.setLookaheadMode(true); XRDS xrds = resolver.resolveAuthToXRDS(msTargetXRI, trustType, followRefs); // ResolveInfo oResolveInfo = resolver.resolveAuth(msTargetXRI, trustType, followRefs); // The non-verbose format is as follows: // // xri://@community*member*family // all subsegments resolved // // resolved subsegment resolved by // ------------------------ -------------------------------------------- // 1. *community http://localhost:8080/xri/resolve?ns=at // 2. *member http://127.0.0.1:8085/xri/resolve?ns=community // 3. *family http://127.0.0.1:8080/xri/resolve?ns=member String sCol1Header = " resolved subsegment"; String sCol2Header = "resolved by"; String sCol1Border = "------------------------"; String sCol2Border = "--------------------------------------------"; String sColGap = " "; String sLeftHeaderPad = " "; // output the trace hops into a separate buffer StringBuilder sTraceHops = new StringBuilder(); int iAuthorityHops = 0; /* Iterator i = oResolveInfo.getChainIterator(); while (i.hasNext()) { ResolveChain oResolveChain = (ResolveChain) i.next(); XRDS oDecriptors = oResolveChain.getXRIDescriptors(); int length = oDecriptors.getNumChildren(); for (int index = 0; index < length; index++) { XRD oDescriptor = oDecriptors.getDescriptorAt(index); if (!mbIsVerbose) { if (sLastResolvedByURI != null) { String sResolved = oDescriptor.getQuery(); int iLeftPad = sCol1Border.length() - sResolved.length(); iLeftPad = (iLeftPad < 0)? 0 : iLeftPad; sTraceHops.append(new Integer(++iAuthorityHops).toString() + ". "); outputChars(sTraceHops, ' ', iLeftPad); sTraceHops.append(sResolved); sTraceHops.append(sColGap); sTraceHops.append(sLastResolvedByURI + "\n"); } sLastResolvedByURI = oDescriptor.getURI().toString(); } else { sTraceHops.append(oDescriptor.toString()); } } // output the xri and the resolution status sOutput.append("\n"); sOutput.append(msTargetXRI + "\n"); if (oResolveInfo.resolvedAll()) { sOutput.append("all subsegments resolved \n"); } else { // handle case where no subsegment is resolved if (iAuthorityHops == 0) { sOutput.append("no subsegments resolved \n\n"); return; } else { String sUnresolvedPart = oResolveInfo.getUnresolved(); sOutput.append("unresolved subsegments: " + sUnresolvedPart + "\n"); } } // output the header sOutput.append("\n"); if (!mbDontOutputHeader && !mbIsVerbose) { sOutput.append( sLeftHeaderPad + sCol1Header + sColGap + sCol2Header + "\n" + sLeftHeaderPad + sCol1Border + sColGap + sCol2Border + "\n" ); } // output the trace hops sOutput.append(sTraceHops); } sOutput.append("\n"); */ } // tracert() /* **************************************************************************** * scanArgs() **************************************************************************** */ /** * Scans list of command-line arguments, setting member variables for * the data argument, and all options. * @param sArgs - command lines args list * @param sOutput - string buffer for error message, if false returned * * @return SUCCESS or FAILURE */ private int scanArgs(StringBuilder sOutput, String[] sArgs) { for (int i = 0; i < sArgs.length; i++) { String sArg = sArgs[i]; if (!isOption(sArg)) { // set the sole data argment if (msTargetXRI == null) { msTargetXRI = sArg; } else { outputPleaseTypeHelp(sOutput); return FAILURE; } } else if (sArg.equalsIgnoreCase(OPT_VERBOSE)) { mbIsVerbose = true; } else if (sArg.equalsIgnoreCase(OPT_ROOT_AT_URI)) { if (i == sArgs.length || isOption(sArgs[++i])) { outputOptionRequiresArgument(sOutput, OPT_ROOT_AT_URI); return FAILURE; } msRootAtURI = sArgs[i]; } else if (sArg.equalsIgnoreCase(OPT_ROOT_EQUALS_URI)) { if (i == sArgs.length || isOption(sArgs[++i])) { outputOptionRequiresArgument(sOutput, OPT_ROOT_EQUALS_URI); return FAILURE; } msRootEqualsURI = sArgs[i]; } else if (sArg.equalsIgnoreCase(OPT_NO_HEADER)) { mbDontOutputHeader = true; } else { sOutput.append("Invalid option: " + sArg + "\n"); outputPleaseTypeHelp(sOutput); return FAILURE; } } // error if we do not have at least xri if (msTargetXRI == null) { sOutput.append("Must specify target XRI. \n"); outputPleaseTypeHelp(sOutput); return FAILURE; } return SUCCESS; } // scanArgs() /* **************************************************************************** * validateRootURIs() **************************************************************************** */ /** * Validates that connections can be made to the URIs for the at and equal * root authorities. * * @paran sOutput - string buffer containing error information if * FAILURE is returned * * @returns SUCCESS or FAILURE */ private int validateRootURIs(StringBuilder sOutput) { String sCurURI = null; try { sCurURI = msRootEqualsURI; URL oURL = new URL(sCurURI); URLConnection oConn = oURL.openConnection(); oConn.connect(); sCurURI = msRootAtURI; oURL = new URL(sCurURI); oConn = oURL.openConnection(); oConn.connect(); } catch (Throwable oThrowable) { sOutput.append("Cannot cannect to root authority URI: " + sCurURI); return FAILURE; } return SUCCESS; } // validateRootURIs() /* **************************************************************************** * outputUsage() **************************************************************************** */ /** * Outputs the program usage to the given string buffer. */ private void outputUsage(StringBuilder sOutput) { // output the overall program usage sOutput.append( "\n" + "usage: 1. xritracert <XRI> [options] \n" + " 2. xritracert help \n" + "\n" + "The first form resolves the given <XRI> and outputs the URIs for \n" + "the registry servers used at each step of the resolution. \n" + "\n" + "Example usage: xritracert xri://@community*member*family \n" + "\n" + "Refer to the OASIS document \"Extensible Resource Identifier (XRI) \n" + "Resolution\" for information about XRI resolution. \n" + "\n" + "The second form generates this help message. \n" + "\n" + "Available options: \n" + " -root_equals_auth <URI>: Root authority URI for '=' resolution. \n" + " -root_at_auth <URI>: Root authority URI for '@' resolution. \n" + "\n" + " -verbose: Print verbose output. \n" + " -no_header: Omit header from non-verbose output. \n" + "\n" + "The default value (used if unspecified) for the two '-root_' options \n" + "is " + ROOT_DEF_URI + ". \n" + "\n" + "Program output: \n" + " For successful invocation, 0 is returned with program \n" + " output on stdout. Otherwise 1 is returned with error \n" + " message output on stderr. \n" + "\n" + "N.B.: \n" + " The server script \"regexample\" can be used to register \n" + " subsegments and create authorities. \n " + "\n" + "\n" ); } // outputUsage() /* **************************************************************************** * isOption() **************************************************************************** */ /** * Returns true if the given argument string is an option. This is currently * defined as beginning with a dash character. */ private bool isOption(String sArg) { return sArg.charAt(0) == '-'; } // isOption() /* **************************************************************************** * outputPleaseTypeHelp() **************************************************************************** */ /** * Outputs text to the given buffer asking the end user to type * "xriadmin -help". */ private void outputPleaseTypeHelp(StringBuilder sOutput) { sOutput.append("Type \"xritracert help\". \n"); } /* **************************************************************************** * outputOptionRequiresArgument() **************************************************************************** */ /** * Outputs text to the given buffer with text suitable for the given * option argument error. */ private void outputOptionRequiresArgument(StringBuilder sOutput, String sOption) { sOutput.append("Option: " + sOption + " requires argument.\n"); outputPleaseTypeHelp(sOutput); } // outputOptionRequiresArgument() /* **************************************************************************** * outputChars() **************************************************************************** */ /** * Outputs the given number of characters to the output buffer. */ void outputChars(StringBuilder sOutput, char c, int num) { char[] cArray = new char[num]; for (int i = 0; i < num; i++) { cArray[i] = c; } sOutput.append(cArray); } // outputChars() /* **************************************************************************** * outputException() **************************************************************************** */ /** * Formats the given throwable into the given output buffer. */ private void outputException(StringBuilder sOutput, Throwable oThrowable) { String message = oThrowable.getLocalizedMessage(); sOutput.append(oThrowable.getClass().getName() + ": " + message + "\n"); if (mbIsVerbose) { oThrowable.printStackTrace(); } } // outputException() /* **************************************************************************** * exit() **************************************************************************** */ /** * Prints the output of the given buffer and exits the program. * * @param sOutput - text to output */ static private void exit(StringBuilder sOutput, int iStatus) { if (iStatus == FAILURE) { Logger.Error(sOutput); } else { Logger.Info(sOutput); } System.exit(iStatus); } // exit() } // Class: XRITractRt }
// // System.Data.SQLite.SqliteCommand.cs // // Represents a Transact-SQL statement or stored procedure to execute against // a Sqlite database file. // // Author(s): Vladimir Vukicevic <[email protected]> // Everaldo Canuto <[email protected]> // Chris Turchin <[email protected]> // Jeroen Zwartepoorte <[email protected]> // Thomas Zoechling <[email protected]> // Joshua Tauberer <[email protected]> // Noah Hart <[email protected]> // // Copyright (C) 2002 Vladimir Vukicevic // // 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.Text; using System.Data; using System.Data.Common; using System.Data.SQLite; using System.Globalization; namespace System.Data.SQLite { [System.ComponentModel.DesignerCategory("")] public class SQLiteCommand : DbCommand, ICloneable { #region Fields private SQLiteConnection parent_conn; private SQLiteTransaction transaction; private string sql; private SQLiteParameterCollection sql_params; private bool prepared = false; private bool _designTimeVisible = true; #endregion #region Constructors and destructors internal SQLiteCommand() : this(null) { } public SQLiteCommand(SQLiteConnection dbConn) : this (string.Empty, dbConn) { } public SQLiteCommand(string sqlText, SQLiteConnection dbConn) { sql = sqlText; DbConnection = dbConn; } private SQLiteCommand(string sqlText, SQLiteConnection dbConn, SQLiteTransaction trans) { sql = sqlText; parent_conn = dbConn; transaction = trans; } #endregion #region Properties public override string CommandText { get { return sql; } set { sql = value; prepared = false; } } public override int CommandTimeout { get; set; } public override CommandType CommandType { get; set; } protected override DbConnection DbConnection { get { return parent_conn; } set { parent_conn = (SQLiteConnection)value; } } public new SQLiteConnection Connection { get { return parent_conn; } set { parent_conn = value; } } public new SQLiteParameterCollection Parameters { get { if(sql_params == null) sql_params = new SQLiteParameterCollection(); return sql_params; } } protected override DbParameterCollection DbParameterCollection { get { return Parameters; } } protected override DbTransaction DbTransaction { get { return transaction; } set { transaction = (SQLiteTransaction)value; } } public override bool DesignTimeVisible { get; set; } public override UpdateRowSource UpdatedRowSource { get; set; } #endregion #region Internal Methods internal int NumChanges() { //if (parent_conn.Version == 3) return Sqlite3.sqlite3_changes(parent_conn.Handle2); //else // return Sqlite.sqlite_changes(parent_conn.Handle); } private void BindParameters3(Sqlite3.Vdbe pStmt) { if(sql_params == null) return; if(sql_params.Count == 0) return; int pcount = Sqlite3.sqlite3_bind_parameter_count(pStmt); for(int i = 1; i <= pcount; i++) { String name = Sqlite3.sqlite3_bind_parameter_name(pStmt, i); SQLiteParameter param = null; if(!String.IsNullOrEmpty(name)) param = sql_params[name] as SQLiteParameter; else param = sql_params[i - 1] as SQLiteParameter; if(param.Value == null) { Sqlite3.sqlite3_bind_null(pStmt, i); continue; } Type ptype = param.Value.GetType(); if(ptype.IsEnum) ptype = Enum.GetUnderlyingType(ptype); SQLiteError err; if(ptype.Equals(typeof(String))) { String s = (String)param.Value; err = (SQLiteError)Sqlite3.sqlite3_bind_text(pStmt, i, s, -1, null); } else if(ptype.Equals(typeof(DBNull))) { err = (SQLiteError)Sqlite3.sqlite3_bind_null(pStmt, i); } else if(ptype.Equals(typeof(Boolean))) { bool b = (bool)param.Value; err = (SQLiteError)Sqlite3.sqlite3_bind_int(pStmt, i, b ? 1 : 0); } else if(ptype.Equals(typeof(Byte))) { err = (SQLiteError)Sqlite3.sqlite3_bind_int(pStmt, i, (Byte)param.Value); } else if(ptype.Equals(typeof(Char))) { err = (SQLiteError)Sqlite3.sqlite3_bind_int(pStmt, i, (Char)param.Value); } else if(ptype.IsEnum) { err = (SQLiteError)Sqlite3.sqlite3_bind_int(pStmt, i, (Int32)param.Value); } else if(ptype.Equals(typeof(Int16))) { err = (SQLiteError)Sqlite3.sqlite3_bind_int(pStmt, i, (Int16)param.Value); } else if(ptype.Equals(typeof(Int32))) { err = (SQLiteError)Sqlite3.sqlite3_bind_int(pStmt, i, (Int32)param.Value); } else if(ptype.Equals(typeof(SByte))) { err = (SQLiteError)Sqlite3.sqlite3_bind_int(pStmt, i, (SByte)param.Value); } else if(ptype.Equals(typeof(UInt16))) { err = (SQLiteError)Sqlite3.sqlite3_bind_int(pStmt, i, (UInt16)param.Value); } else if(ptype.Equals(typeof(DateTime))) { DateTime dt = (DateTime)param.Value; err = (SQLiteError)Sqlite3.sqlite3_bind_text(pStmt, i, dt.ToString("yyyy-MM-dd HH:mm:ss.fff"), -1, null); } else if(ptype.Equals(typeof(Decimal))) { string val = ((Decimal)param.Value).ToString(CultureInfo.InvariantCulture); err = (SQLiteError)Sqlite3.sqlite3_bind_text(pStmt, i, val, val.Length, null); } else if(ptype.Equals(typeof(Double))) { err = (SQLiteError)Sqlite3.sqlite3_bind_double(pStmt, i, (Double)param.Value); } else if(ptype.Equals(typeof(Single))) { err = (SQLiteError)Sqlite3.sqlite3_bind_double(pStmt, i, (Single)param.Value); } else if(ptype.Equals(typeof(UInt32))) { err = (SQLiteError)Sqlite3.sqlite3_bind_int64(pStmt, i, (UInt32)param.Value); } else if(ptype.Equals(typeof(Int64))) { err = (SQLiteError)Sqlite3.sqlite3_bind_int64(pStmt, i, (Int64)param.Value); } else if(ptype.Equals(typeof(Byte[]))) { err = (SQLiteError)Sqlite3.sqlite3_bind_blob(pStmt, i, (byte[])param.Value, ((byte[])param.Value).Length, null); } else if(ptype.Equals(typeof(Guid))) { err = (SQLiteError)Sqlite3.sqlite3_bind_text(pStmt, i, param.Value.ToString(), param.Value.ToString().Length, null); } else { throw new ApplicationException("Unkown Parameter Type"); } if(err != SQLiteError.OK) { throw new ApplicationException("Sqlite error in bind " + err); } } } private void GetNextStatement(string pzStart, ref string pzTail, ref Sqlite3.Vdbe pStmt) { SQLiteError err = (SQLiteError)Sqlite3.sqlite3_prepare_v2(parent_conn.Handle2, pzStart, pzStart.Length, ref pStmt, ref pzTail); if(err != SQLiteError.OK) throw new SQLiteSyntaxException(parent_conn.Handle2.errCode, GetError3()); } // Executes a statement and ignores its result. private void ExecuteStatement(Sqlite3.Vdbe pStmt) { int cols; IntPtr pazValue, pazColName; ExecuteStatement(pStmt, out cols, out pazValue, out pazColName); } // Executes a statement and returns whether there is more data available. internal bool ExecuteStatement(Sqlite3.Vdbe pStmt, out int cols, out IntPtr pazValue, out IntPtr pazColName) { SQLiteError err; //if (parent_conn.Version == 3) //{ err = (SQLiteError)Sqlite3.sqlite3_step(pStmt); if(err == SQLiteError.ERROR) throw new SQLiteExecutionException(parent_conn.Handle2.errCode, GetError3() + "\n" + pStmt.zErrMsg); pazValue = IntPtr.Zero; pazColName = IntPtr.Zero; // not used for v=3 cols = Sqlite3.sqlite3_column_count(pStmt); /* } else { err = (SqliteError)Sqlite3.sqlite3_step(pStmt, out cols, out pazValue, out pazColName); if (err == SqliteError.ERROR) throw new SqliteExecutionException (); } */ if(err == SQLiteError.BUSY) throw new SQLiteBusyException(); if(err == SQLiteError.MISUSE) throw new SQLiteExecutionException(); if(err == SQLiteError.CONSTRAINT) throw new SQLiteException(parent_conn.Handle2.errCode, GetError3() + "\n" + pStmt.zErrMsg); if(err == SQLiteError.MISMATCH) throw new SQLiteException(parent_conn.Handle2.errCode, GetError3() + "\n" + pStmt.zErrMsg); // err is either ROW or DONE. return err == SQLiteError.ROW; } #endregion #region Public Methods object ICloneable.Clone() { var res = new SQLiteCommand(sql, parent_conn, transaction); res.sql_params = this.sql_params; return res; } public override void Cancel() { } public override void Prepare() { // There isn't much we can do here. If a table schema // changes after preparing a statement, Sqlite bails, // so we can only compile statements right before we // want to run them. if(parent_conn == null) { throw new InvalidOperationException("Can not use object without providing DbConnection"); } if(prepared) return; prepared = true; } protected override DbParameter CreateDbParameter() { return new SQLiteParameter(); } public override int ExecuteNonQuery() { int rows_affected; ExecuteReader(CommandBehavior.Default, false, out rows_affected); return rows_affected; } public override object ExecuteScalar() { SQLiteDataReader r = (SQLiteDataReader)ExecuteReader(); if(r == null || !r.Read()) { return null; } object o = r[0]; r.Close(); return o; } public new SQLiteDataReader ExecuteReader(CommandBehavior behavior) { int r; return ExecuteReader(behavior, true, out r); } public new SQLiteDataReader ExecuteReader() { return ExecuteReader(CommandBehavior.Default); } protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { return ExecuteReader(behavior); } public SQLiteDataReader ExecuteReader(CommandBehavior behavior, bool want_results, out int rows_affected) { Prepare(); // The SQL string may contain multiple sql commands, so the main // thing to do is have Sqlite iterate through the commands. // If want_results, only the last command is returned as a // DataReader. Otherwise, no command is returned as a // DataReader. //IntPtr psql; // pointer to SQL command // Sqlite 2 docs say this: By default, SQLite assumes that all data uses a fixed-size 8-bit // character (iso8859). But if you give the --enable-utf8 option to the configure script, then the // library assumes UTF-8 variable sized characters. This makes a difference for the LIKE and GLOB // operators and the LENGTH() and SUBSTR() functions. The static string sqlite_encoding will be set // to either "UTF-8" or "iso8859" to indicate how the library was compiled. In addition, the sqlite.h // header file will define one of the macros SQLITE_UTF8 or SQLITE_ISO8859, as appropriate. // // We have no way of knowing whether Sqlite 2 expects ISO8859 or UTF-8, but ISO8859 seems to be the // default. Therefore, we need to use an ISO8859(-1) compatible encoding, like ANSI. // OTOH, the user may want to specify the encoding of the bytes stored in the database, regardless // of what Sqlite is treating them as, // For Sqlite 3, we use the UTF-16 prepare function, so we need a UTF-16 string. /* if (parent_conn.Version == 2) psql = Sqlite.StringToHeap (sql.Trim(), parent_conn.Encoding); else psql = Marshal.StringToHGlobalUni (sql.Trim()); */ string queryval = sql.Trim(); string pzTail = sql.Trim(); IntPtr errMsgPtr; parent_conn.StartExec(); rows_affected = 0; try { while(true) { Sqlite3.Vdbe pStmt = null; queryval = pzTail; GetNextStatement(queryval, ref pzTail, ref pStmt); if(pStmt == null) throw new Exception(); // pzTail is positioned after the last byte in the // statement, which will be the NULL character if // this was the last statement. bool last = pzTail.Length == 0; try { if(parent_conn.Version == 3) BindParameters3(pStmt); if(last && want_results) return new SQLiteDataReader(this, pStmt, parent_conn.Version); ExecuteStatement(pStmt); if(last) // rows_affected is only used if !want_results rows_affected = NumChanges(); } finally { //if (parent_conn.Version == 3) Sqlite3.sqlite3_finalize(pStmt); //else // Sqlite.sqlite_finalize (pStmt, out errMsgPtr); } if(last) break; } return null; } //alxwest: Console.WriteLine in shared functionality. //catch ( Exception ex ) //{ // Console.WriteLine( ex.Message ); // return null; //} finally { parent_conn.EndExec(); //Marshal.FreeHGlobal (psql); } } public int LastInsertRowID() { return parent_conn.LastInsertRowId; } public string GetLastError() { return Sqlite3.sqlite3_errmsg(parent_conn.Handle2); } private string GetError3() { return Sqlite3.sqlite3_errmsg(parent_conn.Handle2); //return Marshal.PtrToStringUni (Sqlite.sqlite3_errmsg16 (parent_conn.Handle)); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using NPoco; using Umbraco.Cms.Core.Configuration; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Notifications; using Umbraco.Cms.Infrastructure.Migrations.Notifications; using Umbraco.Cms.Infrastructure.Persistence; using Umbraco.Cms.Infrastructure.Persistence.DatabaseModelDefinitions; using Umbraco.Cms.Infrastructure.Persistence.Dtos; using Umbraco.Cms.Infrastructure.Persistence.SqlSyntax; using Umbraco.Extensions; using ColumnInfo = Umbraco.Cms.Infrastructure.Persistence.SqlSyntax.ColumnInfo; namespace Umbraco.Cms.Infrastructure.Migrations.Install { /// <summary> /// Creates the initial database schema during install. /// </summary> public class DatabaseSchemaCreator { // all tables, in order internal static readonly List<Type> OrderedTables = new() { typeof(UserDto), typeof(NodeDto), typeof(ContentTypeDto), typeof(TemplateDto), typeof(ContentDto), typeof(ContentVersionDto), typeof(MediaVersionDto), typeof(DocumentDto), typeof(ContentTypeTemplateDto), typeof(DataTypeDto), typeof(DictionaryDto), typeof(LanguageDto), typeof(LanguageTextDto), typeof(DomainDto), typeof(LogDto), typeof(MacroDto), typeof(MacroPropertyDto), typeof(MemberPropertyTypeDto), typeof(MemberDto), typeof(Member2MemberGroupDto), typeof(PropertyTypeGroupDto), typeof(PropertyTypeDto), typeof(PropertyDataDto), typeof(RelationTypeDto), typeof(RelationDto), typeof(TagDto), typeof(TagRelationshipDto), typeof(ContentType2ContentTypeDto), typeof(ContentTypeAllowedContentTypeDto), typeof(User2NodeNotifyDto), typeof(ServerRegistrationDto), typeof(AccessDto), typeof(AccessRuleDto), typeof(CacheInstructionDto), typeof(ExternalLoginDto), typeof(ExternalLoginTokenDto), typeof(TwoFactorLoginDto), typeof(RedirectUrlDto), typeof(LockDto), typeof(UserGroupDto), typeof(User2UserGroupDto), typeof(UserGroup2NodePermissionDto), typeof(UserGroup2AppDto), typeof(UserStartNodeDto), typeof(ContentNuDto), typeof(DocumentVersionDto), typeof(KeyValueDto), typeof(UserLoginDto), typeof(ConsentDto), typeof(AuditEntryDto), typeof(ContentVersionCultureVariationDto), typeof(DocumentCultureVariationDto), typeof(ContentScheduleDto), typeof(LogViewerQueryDto), typeof(ContentVersionCleanupPolicyDto), typeof(UserGroup2NodeDto), typeof(CreatedPackageSchemaDto) }; private readonly IUmbracoDatabase _database; private readonly IEventAggregator _eventAggregator; private readonly ILogger<DatabaseSchemaCreator> _logger; private readonly ILoggerFactory _loggerFactory; private readonly IUmbracoVersion _umbracoVersion; public DatabaseSchemaCreator(IUmbracoDatabase database, ILogger<DatabaseSchemaCreator> logger, ILoggerFactory loggerFactory, IUmbracoVersion umbracoVersion, IEventAggregator eventAggregator) { _database = database ?? throw new ArgumentNullException(nameof(database)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); _umbracoVersion = umbracoVersion ?? throw new ArgumentNullException(nameof(umbracoVersion)); _eventAggregator = eventAggregator; if (_database?.SqlContext?.SqlSyntax == null) { throw new InvalidOperationException("No SqlContext has been assigned to the database"); } } private ISqlSyntaxProvider SqlSyntax => _database.SqlContext.SqlSyntax; /// <summary> /// Drops all Umbraco tables in the db. /// </summary> internal void UninstallDatabaseSchema() { _logger.LogInformation("Start UninstallDatabaseSchema"); foreach (Type table in OrderedTables.AsEnumerable().Reverse()) { TableNameAttribute tableNameAttribute = table.FirstAttribute<TableNameAttribute>(); var tableName = tableNameAttribute == null ? table.Name : tableNameAttribute.Value; _logger.LogInformation("Uninstall {TableName}", tableName); try { if (TableExists(tableName)) { DropTable(tableName); } } catch (Exception ex) { //swallow this for now, not sure how best to handle this with diff databases... though this is internal // and only used for unit tests. If this fails its because the table doesn't exist... generally! _logger.LogError(ex, "Could not drop table {TableName}", tableName); } } } /// <summary> /// Initializes the database by creating the umbraco db schema. /// </summary> /// <remarks>This needs to execute as part of a transaction.</remarks> public void InitializeDatabaseSchema() { if (!_database.InTransaction) { throw new InvalidOperationException("Database is not in a transaction."); } var eventMessages = new EventMessages(); var creatingNotification = new DatabaseSchemaCreatingNotification(eventMessages); FireBeforeCreation(creatingNotification); if (creatingNotification.Cancel == false) { var dataCreation = new DatabaseDataCreator(_database, _loggerFactory.CreateLogger<DatabaseDataCreator>(), _umbracoVersion); foreach (Type table in OrderedTables) { CreateTable(false, table, dataCreation); } } DatabaseSchemaCreatedNotification createdNotification = new DatabaseSchemaCreatedNotification(eventMessages).WithStateFrom(creatingNotification); FireAfterCreation(createdNotification); } /// <summary> /// Validates the schema of the current database. /// </summary> internal DatabaseSchemaResult ValidateSchema() => ValidateSchema(OrderedTables); internal DatabaseSchemaResult ValidateSchema(IEnumerable<Type> orderedTables) { var result = new DatabaseSchemaResult(); result.IndexDefinitions.AddRange(SqlSyntax.GetDefinedIndexes(_database) .Select(x => new DbIndexDefinition(x))); result.TableDefinitions.AddRange(orderedTables .Select(x => DefinitionFactory.GetTableDefinition(x, SqlSyntax))); ValidateDbTables(result); ValidateDbColumns(result); ValidateDbIndexes(result); ValidateDbConstraints(result); return result; } /// <summary> /// This validates the Primary/Foreign keys in the database /// </summary> /// <param name="result"></param> /// <remarks> /// This does not validate any database constraints that are not PKs or FKs because Umbraco does not create a database /// with non PK/FK constraints. /// Any unique "constraints" in the database are done with unique indexes. /// </remarks> private void ValidateDbConstraints(DatabaseSchemaResult result) { //Check constraints in configured database against constraints in schema var constraintsInDatabase = SqlSyntax.GetConstraintsPerColumn(_database).DistinctBy(x => x.Item3).ToList(); var foreignKeysInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("FK_")) .Select(x => x.Item3).ToList(); var primaryKeysInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("PK_")) .Select(x => x.Item3).ToList(); var unknownConstraintsInDatabase = constraintsInDatabase.Where( x => x.Item3.InvariantStartsWith("FK_") == false && x.Item3.InvariantStartsWith("PK_") == false && x.Item3.InvariantStartsWith("IX_") == false).Select(x => x.Item3).ToList(); var foreignKeysInSchema = result.TableDefinitions.SelectMany(x => x.ForeignKeys.Select(y => y.Name)).ToList(); var primaryKeysInSchema = result.TableDefinitions.SelectMany(x => x.Columns.Select(y => y.PrimaryKeyName)) .Where(x => x.IsNullOrWhiteSpace() == false).ToList(); // Add valid and invalid foreign key differences to the result object // We'll need to do invariant contains with case insensitivity because foreign key, primary key is not standardized // In theory you could have: FK_ or fk_ ...or really any standard that your development department (or developer) chooses to use. foreach (var unknown in unknownConstraintsInDatabase) { if (foreignKeysInSchema.InvariantContains(unknown) || primaryKeysInSchema.InvariantContains(unknown)) { result.ValidConstraints.Add(unknown); } else { result.Errors.Add(new Tuple<string, string>("Unknown", unknown)); } } //Foreign keys: IEnumerable<string> validForeignKeyDifferences = foreignKeysInDatabase.Intersect(foreignKeysInSchema, StringComparer.InvariantCultureIgnoreCase); foreach (var foreignKey in validForeignKeyDifferences) { result.ValidConstraints.Add(foreignKey); } IEnumerable<string> invalidForeignKeyDifferences = foreignKeysInDatabase.Except(foreignKeysInSchema, StringComparer.InvariantCultureIgnoreCase) .Union(foreignKeysInSchema.Except(foreignKeysInDatabase, StringComparer.InvariantCultureIgnoreCase)); foreach (var foreignKey in invalidForeignKeyDifferences) { result.Errors.Add(new Tuple<string, string>("Constraint", foreignKey)); } //Primary keys: //Add valid and invalid primary key differences to the result object IEnumerable<string> validPrimaryKeyDifferences = primaryKeysInDatabase.Intersect(primaryKeysInSchema, StringComparer.InvariantCultureIgnoreCase); foreach (var primaryKey in validPrimaryKeyDifferences) { result.ValidConstraints.Add(primaryKey); } IEnumerable<string> invalidPrimaryKeyDifferences = primaryKeysInDatabase.Except(primaryKeysInSchema, StringComparer.InvariantCultureIgnoreCase) .Union(primaryKeysInSchema.Except(primaryKeysInDatabase, StringComparer.InvariantCultureIgnoreCase)); foreach (var primaryKey in invalidPrimaryKeyDifferences) { result.Errors.Add(new Tuple<string, string>("Constraint", primaryKey)); } } private void ValidateDbColumns(DatabaseSchemaResult result) { //Check columns in configured database against columns in schema IEnumerable<ColumnInfo> columnsInDatabase = SqlSyntax.GetColumnsInSchema(_database); var columnsPerTableInDatabase = columnsInDatabase.Select(x => string.Concat(x.TableName, ",", x.ColumnName)).ToList(); var columnsPerTableInSchema = result.TableDefinitions .SelectMany(x => x.Columns.Select(y => string.Concat(y.TableName, ",", y.Name))).ToList(); //Add valid and invalid column differences to the result object IEnumerable<string> validColumnDifferences = columnsPerTableInDatabase.Intersect(columnsPerTableInSchema, StringComparer.InvariantCultureIgnoreCase); foreach (var column in validColumnDifferences) { result.ValidColumns.Add(column); } IEnumerable<string> invalidColumnDifferences = columnsPerTableInDatabase.Except(columnsPerTableInSchema, StringComparer.InvariantCultureIgnoreCase) .Union(columnsPerTableInSchema.Except(columnsPerTableInDatabase, StringComparer.InvariantCultureIgnoreCase)); foreach (var column in invalidColumnDifferences) { result.Errors.Add(new Tuple<string, string>("Column", column)); } } private void ValidateDbTables(DatabaseSchemaResult result) { //Check tables in configured database against tables in schema var tablesInDatabase = SqlSyntax.GetTablesInSchema(_database).ToList(); var tablesInSchema = result.TableDefinitions.Select(x => x.Name).ToList(); //Add valid and invalid table differences to the result object IEnumerable<string> validTableDifferences = tablesInDatabase.Intersect(tablesInSchema, StringComparer.InvariantCultureIgnoreCase); foreach (var tableName in validTableDifferences) { result.ValidTables.Add(tableName); } IEnumerable<string> invalidTableDifferences = tablesInDatabase.Except(tablesInSchema, StringComparer.InvariantCultureIgnoreCase) .Union(tablesInSchema.Except(tablesInDatabase, StringComparer.InvariantCultureIgnoreCase)); foreach (var tableName in invalidTableDifferences) { result.Errors.Add(new Tuple<string, string>("Table", tableName)); } } private void ValidateDbIndexes(DatabaseSchemaResult result) { //These are just column indexes NOT constraints or Keys //var colIndexesInDatabase = result.DbIndexDefinitions.Where(x => x.IndexName.InvariantStartsWith("IX_")).Select(x => x.IndexName).ToList(); var colIndexesInDatabase = result.IndexDefinitions.Select(x => x.IndexName).ToList(); var indexesInSchema = result.TableDefinitions.SelectMany(x => x.Indexes.Select(y => y.Name)).ToList(); //Add valid and invalid index differences to the result object IEnumerable<string> validColIndexDifferences = colIndexesInDatabase.Intersect(indexesInSchema, StringComparer.InvariantCultureIgnoreCase); foreach (var index in validColIndexDifferences) { result.ValidIndexes.Add(index); } IEnumerable<string> invalidColIndexDifferences = colIndexesInDatabase.Except(indexesInSchema, StringComparer.InvariantCultureIgnoreCase) .Union(indexesInSchema.Except(colIndexesInDatabase, StringComparer.InvariantCultureIgnoreCase)); foreach (var index in invalidColIndexDifferences) { result.Errors.Add(new Tuple<string, string>("Index", index)); } } #region Notifications /// <summary> /// Publishes the <see cref="Notifications.DatabaseSchemaCreatingNotification" /> notification. /// </summary> /// <param name="notification">Cancelable notification marking the creation having begun.</param> internal virtual void FireBeforeCreation(DatabaseSchemaCreatingNotification notification) => _eventAggregator.Publish(notification); /// <summary> /// Publishes the <see cref="DatabaseSchemaCreatedNotification" /> notification. /// </summary> /// <param name="notification">Notification marking the creation having completed.</param> internal virtual void FireAfterCreation(DatabaseSchemaCreatedNotification notification) => _eventAggregator.Publish(notification); #endregion #region Utilities /// <summary> /// Returns whether a table with the specified <paramref name="tableName" /> exists in the database. /// </summary> /// <param name="tableName">The name of the table.</param> /// <returns><c>true</c> if the table exists; otherwise <c>false</c>.</returns> /// <example> /// <code> /// if (schemaHelper.TableExist("MyTable")) /// { /// // do something when the table exists /// } /// </code> /// </example> public bool TableExists(string tableName) => SqlSyntax.DoesTableExist(_database, tableName); /// <summary> /// Returns whether the table for the specified <typeparamref name="T" /> exists in the database. /// </summary> /// <typeparam name="T">The type representing the DTO/table.</typeparam> /// <returns><c>true</c> if the table exists; otherwise <c>false</c>.</returns> /// <example> /// <code> /// if (schemaHelper.TableExist&lt;MyDto&gt;) /// { /// // do something when the table exists /// } /// </code> /// </example> /// <remarks> /// If <typeparamref name="T" /> has been decorated with an <see cref="TableNameAttribute" />, the name from that /// attribute will be used for the table name. If the attribute is not present, the name /// <typeparamref name="T" /> will be used instead. /// </remarks> public bool TableExists<T>() { TableDefinition table = DefinitionFactory.GetTableDefinition(typeof(T), SqlSyntax); return table != null && TableExists(table.Name); } /// <summary> /// Creates a new table in the database based on the type of <typeparamref name="T" />. /// </summary> /// <typeparam name="T">The type representing the DTO/table.</typeparam> /// <param name="overwrite">Whether the table should be overwritten if it already exists.</param> /// <remarks> /// If <typeparamref name="T" /> has been decorated with an <see cref="TableNameAttribute" />, the name from that /// attribute will be used for the table name. If the attribute is not present, the name /// <typeparamref name="T" /> will be used instead. /// If a table with the same name already exists, the <paramref name="overwrite" /> parameter will determine /// whether the table is overwritten. If <c>true</c>, the table will be overwritten, whereas this method will /// not do anything if the parameter is <c>false</c>. /// </remarks> internal void CreateTable<T>(bool overwrite = false) where T : new() { Type tableType = typeof(T); CreateTable(overwrite, tableType, new DatabaseDataCreator(_database, _loggerFactory.CreateLogger<DatabaseDataCreator>(), _umbracoVersion)); } /// <summary> /// Creates a new table in the database for the specified <paramref name="modelType" />. /// </summary> /// <param name="overwrite">Whether the table should be overwritten if it already exists.</param> /// <param name="modelType">The representing the table.</param> /// <param name="dataCreation"></param> /// <remarks> /// If <paramref name="modelType" /> has been decorated with an <see cref="TableNameAttribute" />, the name from /// that attribute will be used for the table name. If the attribute is not present, the name /// <paramref name="modelType" /> will be used instead. /// If a table with the same name already exists, the <paramref name="overwrite" /> parameter will determine /// whether the table is overwritten. If <c>true</c>, the table will be overwritten, whereas this method will /// not do anything if the parameter is <c>false</c>. /// This need to execute as part of a transaction. /// </remarks> internal void CreateTable(bool overwrite, Type modelType, DatabaseDataCreator dataCreation) { if (!_database.InTransaction) { throw new InvalidOperationException("Database is not in a transaction."); } TableDefinition tableDefinition = DefinitionFactory.GetTableDefinition(modelType, SqlSyntax); var tableName = tableDefinition.Name; var createSql = SqlSyntax.Format(tableDefinition); var createPrimaryKeySql = SqlSyntax.FormatPrimaryKey(tableDefinition); List<string> foreignSql = SqlSyntax.Format(tableDefinition.ForeignKeys); List<string> indexSql = SqlSyntax.Format(tableDefinition.Indexes); var tableExist = TableExists(tableName); if (overwrite && tableExist) { _logger.LogInformation("Table {TableName} already exists, but will be recreated", tableName); DropTable(tableName); tableExist = false; } if (tableExist) { // The table exists and was not recreated/overwritten. _logger.LogInformation("Table {TableName} already exists - no changes were made", tableName); return; } //Execute the Create Table sql _database.Execute(new Sql(createSql)); _logger.LogInformation("Create Table {TableName}: \n {Sql}", tableName, createSql); //If any statements exists for the primary key execute them here if (string.IsNullOrEmpty(createPrimaryKeySql) == false) { _database.Execute(new Sql(createPrimaryKeySql)); _logger.LogInformation("Create Primary Key:\n {Sql}", createPrimaryKeySql); } if (SqlSyntax.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity)) { _database.Execute(new Sql($"SET IDENTITY_INSERT {SqlSyntax.GetQuotedTableName(tableName)} ON ")); } //Call the NewTable-event to trigger the insert of base/default data //OnNewTable(tableName, _db, e, _logger); dataCreation.InitializeBaseData(tableName); if (SqlSyntax.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity)) { _database.Execute(new Sql($"SET IDENTITY_INSERT {SqlSyntax.GetQuotedTableName(tableName)} OFF;")); } //Loop through index statements and execute sql foreach (var sql in indexSql) { _database.Execute(new Sql(sql)); _logger.LogInformation("Create Index:\n {Sql}", sql); } //Loop through foreignkey statements and execute sql foreach (var sql in foreignSql) { _database.Execute(new Sql(sql)); _logger.LogInformation("Create Foreign Key:\n {Sql}", sql); } if (overwrite) { _logger.LogInformation("Table {TableName} was recreated", tableName); } else { _logger.LogInformation("New table {TableName} was created", tableName); } } /// <summary> /// Drops the table for the specified <typeparamref name="T" />. /// </summary> /// <typeparam name="T">The type representing the DTO/table.</typeparam> /// <example> /// <code> /// schemaHelper.DropTable&lt;MyDto&gt;); /// </code> /// </example> /// <remarks> /// If <typeparamref name="T" /> has been decorated with an <see cref="TableNameAttribute" />, the name from that /// attribute will be used for the table name. If the attribute is not present, the name /// <typeparamref name="T" /> will be used instead. /// </remarks> public void DropTable(string tableName) { var sql = new Sql(string.Format(SqlSyntax.DropTable, SqlSyntax.GetQuotedTableName(tableName))); _database.Execute(sql); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace StorageDemo.Api.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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.Xml.Serialization { using System.IO; using System; using System.Collections; using System.ComponentModel; using System.Xml; public delegate void XmlAttributeEventHandler(object sender, XmlAttributeEventArgs e); public class XmlAttributeEventArgs : EventArgs { private readonly object _o; private readonly XmlAttribute _attr; private readonly string _qnames; private readonly int _lineNumber; private readonly int _linePosition; internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePosition, object o, string qnames) { _attr = attr; _o = o; _qnames = qnames; _lineNumber = lineNumber; _linePosition = linePosition; } public object ObjectBeingDeserialized { get { return _o; } } public XmlAttribute Attr { get { return _attr; } } /// <summary> /// Gets the current line number. /// </summary> public int LineNumber { get { return _lineNumber; } } /// <summary> /// Gets the current line position. /// </summary> public int LinePosition { get { return _linePosition; } } /// <summary> /// List the qnames of attributes expected in the current context. /// </summary> public string ExpectedAttributes { get { return _qnames == null ? string.Empty : _qnames; } } } public delegate void XmlElementEventHandler(object sender, XmlElementEventArgs e); public class XmlElementEventArgs : EventArgs { private readonly object _o; private readonly XmlElement _elem; private readonly string _qnames; private readonly int _lineNumber; private readonly int _linePosition; internal XmlElementEventArgs(XmlElement elem, int lineNumber, int linePosition, object o, string qnames) { _elem = elem; _o = o; _qnames = qnames; _lineNumber = lineNumber; _linePosition = linePosition; } public object ObjectBeingDeserialized { get { return _o; } } public XmlElement Element { get { return _elem; } } public int LineNumber { get { return _lineNumber; } } public int LinePosition { get { return _linePosition; } } /// <summary> /// List of qnames of elements expected in the current context. /// </summary> public string ExpectedElements { get { return _qnames == null ? string.Empty : _qnames; } } } public delegate void XmlNodeEventHandler(object sender, XmlNodeEventArgs e); public class XmlNodeEventArgs : EventArgs { private readonly object _o; private readonly XmlNode _xmlNode; private readonly int _lineNumber; private readonly int _linePosition; internal XmlNodeEventArgs(XmlNode xmlNode, int lineNumber, int linePosition, object o) { _o = o; _xmlNode = xmlNode; _lineNumber = lineNumber; _linePosition = linePosition; } public object ObjectBeingDeserialized { get { return _o; } } public XmlNodeType NodeType { get { return _xmlNode.NodeType; } } public string Name { get { return _xmlNode.Name; } } public string LocalName { get { return _xmlNode.LocalName; } } public string NamespaceURI { get { return _xmlNode.NamespaceURI; } } public string Text { get { return _xmlNode.Value; } } /// <summary> /// Gets the current line number. /// </summary> public int LineNumber { get { return _lineNumber; } } /// <summary> /// Gets the current line position. /// </summary> public int LinePosition { get { return _linePosition; } } } public delegate void UnreferencedObjectEventHandler(object sender, UnreferencedObjectEventArgs e); public class UnreferencedObjectEventArgs : EventArgs { private readonly object _o; private readonly string _id; public UnreferencedObjectEventArgs(object o, string id) { _o = o; _id = id; } public object UnreferencedObject { get { return _o; } } public string UnreferencedId { get { return _id; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // </copyright> // <summary>Tests for ProjectItem</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Build.UnitTests.OM.Definition { /// <summary> /// Tests for ProjectItem /// </summary> [TestClass] public class ProjectItem_Tests { /// <summary> /// Gets or sets the test context, assigned by the MSTest test runner. /// </summary> public TestContext TestContext { get; set; } /// <summary> /// Project getter /// </summary> [TestMethod] public void ProjectGetter() { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; Assert.AreEqual(true, Object.ReferenceEquals(project, item.Project)); } /// <summary> /// No metadata, simple case /// </summary> [TestMethod] public void NoMetadata() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'/> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); Assert.IsNotNull(item.Xml); Assert.AreEqual("i", item.ItemType); Assert.AreEqual("i1", item.EvaluatedInclude); Assert.AreEqual("i1", item.UnevaluatedInclude); Assert.AreEqual(false, item.Metadata.GetEnumerator().MoveNext()); } /// <summary> /// Read off metadata /// </summary> [TestMethod] public void ReadMetadata() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m1>v1</m1> <m2>v2</m2> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); var itemMetadata = Helpers.MakeList(item.Metadata); Assert.AreEqual(2, itemMetadata.Count); Assert.AreEqual("m1", itemMetadata[0].Name); Assert.AreEqual("m2", itemMetadata[1].Name); Assert.AreEqual("v1", itemMetadata[0].EvaluatedValue); Assert.AreEqual("v2", itemMetadata[1].EvaluatedValue); Assert.AreEqual(itemMetadata[0], item.GetMetadata("m1")); Assert.AreEqual(itemMetadata[1], item.GetMetadata("m2")); } /// <summary> /// Get metadata inherited from item definitions /// </summary> [TestMethod] public void GetMetadataObjectsFromDefinition() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <m0>v0</m0> <m1>v1</m1> </i> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'> <m1>v1b</m1> <m2>v2</m2> </i> </ItemGroup> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectItem item = Helpers.GetFirst(project.GetItems("i")); ProjectMetadata m0 = item.GetMetadata("m0"); ProjectMetadata m1 = item.GetMetadata("m1"); ProjectItemDefinition definition = project.ItemDefinitions["i"]; ProjectMetadata idm0 = definition.GetMetadata("m0"); ProjectMetadata idm1 = definition.GetMetadata("m1"); Assert.AreEqual(true, Object.ReferenceEquals(m0, idm0)); Assert.AreEqual(false, Object.ReferenceEquals(m1, idm1)); } /// <summary> /// Get metadata values inherited from item definitions /// </summary> [TestMethod] public void GetMetadataValuesFromDefinition() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <m0>v0</m0> <m1>v1</m1> </i> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'> <m1>v1b</m1> <m2>v2</m2> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); Assert.AreEqual("v0", item.GetMetadataValue("m0")); Assert.AreEqual("v1b", item.GetMetadataValue("m1")); Assert.AreEqual("v2", item.GetMetadataValue("m2")); } /// <summary> /// Getting nonexistent metadata should return null /// </summary> [TestMethod] public void GetNonexistentMetadata() { ProjectItem item = GetOneItemFromFragment(@"<i Include='i0'/>"); Assert.AreEqual(null, item.GetMetadata("m0")); } /// <summary> /// Getting value of nonexistent metadata should return String.Empty /// </summary> [TestMethod] public void GetNonexistentMetadataValue() { ProjectItem item = GetOneItemFromFragment(@"<i Include='i0'/>"); Assert.AreEqual(String.Empty, item.GetMetadataValue("m0")); } /// <summary> /// Attempting to set metadata with an invalid XML name should fail /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentException))] public void SetInvalidXmlNameMetadata() { ProjectItem item = GetOneItemFromFragment(@"<i Include='c:\foo\bar.baz'/>"); item.SetMetadataValue("##invalid##", "x"); } /// <summary> /// Attempting to set built-in metadata should fail /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentException))] public void SetInvalidBuiltInMetadata() { ProjectItem item = GetOneItemFromFragment(@"<i Include='c:\foo\bar.baz'/>"); item.SetMetadataValue("FullPath", "x"); } /// <summary> /// Attempting to set reserved metadata should fail /// </summary> [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void SetInvalidReservedMetadata() { ProjectItem item = GetOneItemFromFragment(@"<i Include='c:\foo\bar.baz'/>"); item.SetMetadataValue("Choose", "x"); } /// <summary> /// Metadata enumerator should only return custom metadata /// </summary> [TestMethod] public void MetadataEnumeratorExcludesBuiltInMetadata() { ProjectItem item = GetOneItemFromFragment(@"<i Include='c:\foo\bar.baz'/>"); Assert.AreEqual(false, item.Metadata.GetEnumerator().MoveNext()); } /// <summary> /// Read off built-in metadata /// </summary> [TestMethod] public void BuiltInMetadata() { ProjectItem item = GetOneItemFromFragment(@"<i Include='c:\foo\bar.baz'/>"); // c:\foo\bar.baz %(FullPath) = full path of item // c:\ %(RootDir) = root directory of item // bar %(Filename) = item filename without extension // .baz %(Extension) = item filename extension // c:\foo\ %(RelativeDir) = item directory as given in item-spec // foo\ %(Directory) = full path of item directory relative to root // [] %(RecursiveDir) = portion of item path that matched a recursive wildcard // c:\foo\bar.baz %(Identity) = item-spec as given // [] %(ModifiedTime) = last write time of item // [] %(CreatedTime) = creation time of item // [] %(AccessedTime) = last access time of item Assert.AreEqual(@"c:\foo\bar.baz", item.GetMetadataValue("FullPath")); Assert.AreEqual(@"c:\", item.GetMetadataValue("RootDir")); Assert.AreEqual(@"bar", item.GetMetadataValue("Filename")); Assert.AreEqual(@".baz", item.GetMetadataValue("Extension")); Assert.AreEqual(@"c:\foo\", item.GetMetadataValue("RelativeDir")); Assert.AreEqual(@"foo\", item.GetMetadataValue("Directory")); Assert.AreEqual(String.Empty, item.GetMetadataValue("RecursiveDir")); Assert.AreEqual(@"c:\foo\bar.baz", item.GetMetadataValue("Identity")); } /// <summary> /// Check file-timestamp related metadata /// </summary> [TestMethod] public void BuiltInMetadataTimes() { string path = null; string fileTimeFormat = "yyyy'-'MM'-'dd HH':'mm':'ss'.'fffffff"; try { path = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); File.WriteAllText(path, String.Empty); FileInfo info = new FileInfo(path); ProjectItem item = GetOneItemFromFragment(@"<i Include='" + path + "'/>"); Assert.AreEqual(info.LastWriteTime.ToString(fileTimeFormat), item.GetMetadataValue("ModifiedTime")); Assert.AreEqual(info.CreationTime.ToString(fileTimeFormat), item.GetMetadataValue("CreatedTime")); Assert.AreEqual(info.LastAccessTime.ToString(fileTimeFormat), item.GetMetadataValue("AccessedTime")); } finally { File.Delete(path); } } /// <summary> /// Test RecursiveDir metadata /// </summary> [TestMethod] public void RecursiveDirMetadata() { string directory = null; string subdirectory = null; string file = null; try { directory = Path.Combine(Path.GetTempPath(), "a"); if (File.Exists(directory)) { File.Delete(directory); } subdirectory = Path.Combine(directory, "b"); if (File.Exists(subdirectory)) { File.Delete(subdirectory); } file = Path.Combine(subdirectory, "c"); Directory.CreateDirectory(subdirectory); File.WriteAllText(file, String.Empty); ProjectItem item = GetOneItemFromFragment("<i Include='" + directory + @"\**\*'/>"); Assert.AreEqual(@"b\", item.GetMetadataValue("RecursiveDir")); Assert.AreEqual("c", item.GetMetadataValue("Filename")); } finally { File.Delete(file); Directory.Delete(subdirectory); Directory.Delete(directory); } } /// <summary> /// Correctly establish the "RecursiveDir" value when the include /// is semicolon separated. /// (This is what requires that the original include fragment [before wildcard /// expansion] is stored in the item.) /// </summary> [TestMethod] public void RecursiveDirWithSemicolonSeparatedInclude() { string directory = null; string subdirectory = null; string file = null; try { directory = Path.Combine(Path.GetTempPath(), "a"); if (File.Exists(directory)) { File.Delete(directory); } subdirectory = Path.Combine(directory, "b"); if (File.Exists(subdirectory)) { File.Delete(subdirectory); } file = Path.Combine(subdirectory, "c"); Directory.CreateDirectory(subdirectory); File.WriteAllText(file, String.Empty); IList<ProjectItem> items = GetItemsFromFragment("<i Include='i0;" + directory + @"\**\*;i2'/>"); Assert.AreEqual(3, items.Count); Assert.AreEqual("i0", items[0].EvaluatedInclude); Assert.AreEqual(@"b\", items[1].GetMetadataValue("RecursiveDir")); Assert.AreEqual("i2", items[2].EvaluatedInclude); } finally { File.Delete(file); Directory.Delete(subdirectory); Directory.Delete(directory); } } /// <summary> /// Basic exclude case /// </summary> [TestMethod] public void Exclude() { IList<ProjectItem> items = GetItemsFromFragment("<i Include='a;b' Exclude='b;c'/>"); Assert.AreEqual(1, items.Count); Assert.AreEqual("a", items[0].EvaluatedInclude); } /// <summary> /// Exclude against an include with item vectors in it /// </summary> [TestMethod] public void ExcludeWithIncludeVector() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='a;b;c'> </i> </ItemGroup> <ItemGroup> <i Include='x;y;z;@(i);u;v;w' Exclude='b;y;v'> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = GetItems(content); // Should contain a, b, c, x, z, a, c, u, w Assert.AreEqual(9, items.Count); AssertEvaluatedIncludes(items, new string[] { "a", "b", "c", "x", "z", "a", "c", "u", "w" }); } /// <summary> /// Exclude with item vectors against an include with item vectors in it /// </summary> [TestMethod] public void ExcludeVectorWithIncludeVector() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='a;b;c'> </i> <j Include='b;y;v' /> </ItemGroup> <ItemGroup> <i Include='x;y;z;@(i);u;v;w' Exclude='x;@(j);w'> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = GetItems(content); // Should contain a, b, c, z, a, c, u Assert.AreEqual(7, items.Count); AssertEvaluatedIncludes(items, new string[] { "a", "b", "c", "z", "a", "c", "u" }); } /// <summary> /// Include and Exclude containing wildcards /// </summary> [TestMethod] public void Wildcards() { string directory = null; string file1 = null; string file2 = null; string file3 = null; try { directory = Path.Combine(Path.GetTempPath(), "ProjectItem_Tests_Wildcards"); Directory.CreateDirectory(directory); file1 = Path.Combine(directory, "a.1"); file2 = Path.Combine(directory, "a.2"); file3 = Path.Combine(directory, "b.1"); File.WriteAllText(file1, String.Empty); File.WriteAllText(file2, String.Empty); File.WriteAllText(file3, String.Empty); IList<ProjectItem> items = GetItemsFromFragment(String.Format(@"<i Include='{0}\a.*' Exclude='{0}\*.1'/>", directory)); Assert.AreEqual(1, items.Count); Assert.AreEqual(String.Format(@"{0}\a.2", directory), items[0].EvaluatedInclude); } finally { File.Delete(file1); File.Delete(file2); File.Delete(file3); Directory.Delete(directory); } } /// <summary> /// Expression like @(x) should clone metadata, but metadata should still point at the original XML objects /// </summary> [TestMethod] public void CopyFromWithItemListExpressionClonesMetadata() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m>m1</m> </i> <j Include='@(i)'/> </ItemGroup> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(content))); project.GetItems("i").First().SetMetadataValue("m", "m2"); ProjectItem item1 = project.GetItems("i").First(); ProjectItem item2 = project.GetItems("j").First(); Assert.AreEqual("m2", item1.GetMetadataValue("m")); Assert.AreEqual("m1", item2.GetMetadataValue("m")); // Should still point at the same XML items Assert.AreEqual(true, Object.ReferenceEquals(item1.GetMetadata("m").Xml, item2.GetMetadata("m").Xml)); } /// <summary> /// Expression like @(x) should not clone metadata, even if the item type is different. /// It's obvious that it shouldn't clone it if the item type is the same. /// If it is different, it doesn't clone it for performance; even if the item definition metadata /// changes later (this is design time), the inheritors of that item definition type /// (even those that have subsequently been transformed to a different itemtype) should see /// the changes, by design. /// Just to make sure we don't change that behavior, we test it here. /// </summary> [TestMethod] public void CopyFromWithItemListExpressionDoesNotCloneDefinitionMetadata() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <m>m1</m> </i> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'/> <i Include='@(i)'/> <i Include=""@(i->'%(identity)')"" /><!-- this will have two items, so setting metadata will split it --> <j Include='@(i)'/> </ItemGroup> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectItem item1 = project.GetItems("i").First(); ProjectItem item1b = project.GetItems("i").ElementAt(1); ProjectItem item1c = project.GetItems("i").ElementAt(2); ProjectItem item2 = project.GetItems("j").First(); Assert.AreEqual("m1", item1.GetMetadataValue("m")); Assert.AreEqual("m1", item1b.GetMetadataValue("m")); Assert.AreEqual("m1", item1c.GetMetadataValue("m")); Assert.AreEqual("m1", item2.GetMetadataValue("m")); project.ItemDefinitions["i"].SetMetadataValue("m", "m2"); // All the items will see this change Assert.AreEqual("m2", item1.GetMetadataValue("m")); Assert.AreEqual("m2", item1b.GetMetadataValue("m")); Assert.AreEqual("m2", item1c.GetMetadataValue("m")); Assert.AreEqual("m2", item2.GetMetadataValue("m")); // And verify we're not still pointing to the definition metadata objects item1.SetMetadataValue("m", "m3"); item1b.SetMetadataValue("m", "m4"); item1c.SetMetadataValue("m", "m5"); item2.SetMetadataValue("m", "m6"); Assert.AreEqual("m2", project.ItemDefinitions["i"].GetMetadataValue("m")); // Should not have been affected } /// <summary> /// Expression like @(x) should not clone metadata, for perf. See comment on test above. /// </summary> [TestMethod] public void CopyFromWithItemListExpressionClonesDefinitionMetadata_Variation() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <m>m1</m> </i> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'/> <i Include=""@(i->'%(identity)')"" /><!-- this will have one item--> <j Include='@(i)'/> </ItemGroup> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectItem item1 = project.GetItems("i").First(); ProjectItem item1b = project.GetItems("i").ElementAt(1); ProjectItem item2 = project.GetItems("j").First(); Assert.AreEqual("m1", item1.GetMetadataValue("m")); Assert.AreEqual("m1", item1b.GetMetadataValue("m")); Assert.AreEqual("m1", item2.GetMetadataValue("m")); project.ItemDefinitions["i"].SetMetadataValue("m", "m2"); // The items should all see this change Assert.AreEqual("m2", item1.GetMetadataValue("m")); Assert.AreEqual("m2", item1b.GetMetadataValue("m")); Assert.AreEqual("m2", item2.GetMetadataValue("m")); // And verify we're not still pointing to the definition metadata objects item1.SetMetadataValue("m", "m3"); item1b.SetMetadataValue("m", "m4"); item2.SetMetadataValue("m", "m6"); Assert.AreEqual("m2", project.ItemDefinitions["i"].GetMetadataValue("m")); // Should not have been affected } /// <summary> /// Repeated copying of items with item definitions should cause the following order of precedence: /// 1) direct metadata on the item /// 2) item definition metadata on the very first item in the chain /// 3) item definition on the next item, and so on until /// 4) item definition metadata on the destination item itself /// </summary> [TestMethod] public void CopyWithItemDefinition() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <l>l1</l> <m>m1</m> <n>n1</n> </i> <j> <m>m2</m> <o>o2</o> <p>p2</p> </j> <k> <n>n3</n> </k> <l/> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'> <l>l0</l> </i> <j Include='@(i)'/> <k Include='@(j)'> <p>p4</p> </k> <l Include='@(k);l1'/> <m Include='@(l)'> <o>o4</o> </m> </ItemGroup> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(content))); Assert.AreEqual("l0", project.GetItems("i").First().GetMetadataValue("l")); Assert.AreEqual("m1", project.GetItems("i").First().GetMetadataValue("m")); Assert.AreEqual("n1", project.GetItems("i").First().GetMetadataValue("n")); Assert.AreEqual("", project.GetItems("i").First().GetMetadataValue("o")); Assert.AreEqual("", project.GetItems("i").First().GetMetadataValue("p")); Assert.AreEqual("l0", project.GetItems("j").First().GetMetadataValue("l")); Assert.AreEqual("m1", project.GetItems("j").First().GetMetadataValue("m")); Assert.AreEqual("n1", project.GetItems("j").First().GetMetadataValue("n")); Assert.AreEqual("o2", project.GetItems("j").First().GetMetadataValue("o")); Assert.AreEqual("p2", project.GetItems("j").First().GetMetadataValue("p")); Assert.AreEqual("l0", project.GetItems("k").First().GetMetadataValue("l")); Assert.AreEqual("m1", project.GetItems("k").First().GetMetadataValue("m")); Assert.AreEqual("n1", project.GetItems("k").First().GetMetadataValue("n")); Assert.AreEqual("o2", project.GetItems("k").First().GetMetadataValue("o")); Assert.AreEqual("p4", project.GetItems("k").First().GetMetadataValue("p")); Assert.AreEqual("l0", project.GetItems("l").First().GetMetadataValue("l")); Assert.AreEqual("m1", project.GetItems("l").First().GetMetadataValue("m")); Assert.AreEqual("n1", project.GetItems("l").First().GetMetadataValue("n")); Assert.AreEqual("o2", project.GetItems("l").First().GetMetadataValue("o")); Assert.AreEqual("p4", project.GetItems("l").First().GetMetadataValue("p")); Assert.AreEqual("", project.GetItems("l").ElementAt(1).GetMetadataValue("l")); Assert.AreEqual("", project.GetItems("l").ElementAt(1).GetMetadataValue("m")); Assert.AreEqual("", project.GetItems("l").ElementAt(1).GetMetadataValue("n")); Assert.AreEqual("", project.GetItems("l").ElementAt(1).GetMetadataValue("o")); Assert.AreEqual("", project.GetItems("l").ElementAt(1).GetMetadataValue("p")); Assert.AreEqual("l0", project.GetItems("m").First().GetMetadataValue("l")); Assert.AreEqual("m1", project.GetItems("m").First().GetMetadataValue("m")); Assert.AreEqual("n1", project.GetItems("m").First().GetMetadataValue("n")); Assert.AreEqual("o4", project.GetItems("m").First().GetMetadataValue("o")); Assert.AreEqual("p4", project.GetItems("m").First().GetMetadataValue("p")); Assert.AreEqual("", project.GetItems("m").ElementAt(1).GetMetadataValue("l")); Assert.AreEqual("", project.GetItems("m").ElementAt(1).GetMetadataValue("m")); Assert.AreEqual("", project.GetItems("m").ElementAt(1).GetMetadataValue("n")); Assert.AreEqual("o4", project.GetItems("m").ElementAt(1).GetMetadataValue("o")); Assert.AreEqual("", project.GetItems("m").ElementAt(1).GetMetadataValue("p")); // Should still point at the same XML metadata Assert.AreEqual(true, Object.ReferenceEquals(project.GetItems("i").First().GetMetadata("l").Xml, project.GetItems("m").First().GetMetadata("l").Xml)); Assert.AreEqual(true, Object.ReferenceEquals(project.GetItems("i").First().GetMetadata("m").Xml, project.GetItems("m").First().GetMetadata("m").Xml)); Assert.AreEqual(true, Object.ReferenceEquals(project.GetItems("i").First().GetMetadata("n").Xml, project.GetItems("m").First().GetMetadata("n").Xml)); Assert.AreEqual(true, Object.ReferenceEquals(project.GetItems("j").First().GetMetadata("o").Xml, project.GetItems("k").First().GetMetadata("o").Xml)); Assert.AreEqual(true, Object.ReferenceEquals(project.GetItems("k").First().GetMetadata("p").Xml, project.GetItems("m").First().GetMetadata("p").Xml)); Assert.AreEqual(true, !Object.ReferenceEquals(project.GetItems("j").First().GetMetadata("p").Xml, project.GetItems("m").First().GetMetadata("p").Xml)); } /// <summary> /// Repeated copying of items with item definitions should cause the following order of precedence: /// 1) direct metadata on the item /// 2) item definition metadata on the very first item in the chain /// 3) item definition on the next item, and so on until /// 4) item definition metadata on the destination item itself /// </summary> [TestMethod] public void CopyWithItemDefinition2() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <l>l1</l> <m>m1</m> <n>n1</n> </i> <j> <m>m2</m> <o>o2</o> <p>p2</p> </j> <k> <n>n3</n> </k> <l/> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'> <l>l0</l> </i> <j Include='@(i)'/> <k Include='@(j)'> <p>p4</p> </k> <l Include='@(k);l1'/> <m Include='@(l)'> <o>o4</o> </m> </ItemGroup> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(content))); Assert.AreEqual("l0", project.GetItems("i").First().GetMetadataValue("l")); Assert.AreEqual("m1", project.GetItems("i").First().GetMetadataValue("m")); Assert.AreEqual("n1", project.GetItems("i").First().GetMetadataValue("n")); Assert.AreEqual("", project.GetItems("i").First().GetMetadataValue("o")); Assert.AreEqual("", project.GetItems("i").First().GetMetadataValue("p")); Assert.AreEqual("l0", project.GetItems("j").First().GetMetadataValue("l")); Assert.AreEqual("m1", project.GetItems("j").First().GetMetadataValue("m")); Assert.AreEqual("n1", project.GetItems("j").First().GetMetadataValue("n")); Assert.AreEqual("o2", project.GetItems("j").First().GetMetadataValue("o")); Assert.AreEqual("p2", project.GetItems("j").First().GetMetadataValue("p")); Assert.AreEqual("l0", project.GetItems("k").First().GetMetadataValue("l")); Assert.AreEqual("m1", project.GetItems("k").First().GetMetadataValue("m")); Assert.AreEqual("n1", project.GetItems("k").First().GetMetadataValue("n")); Assert.AreEqual("o2", project.GetItems("k").First().GetMetadataValue("o")); Assert.AreEqual("p4", project.GetItems("k").First().GetMetadataValue("p")); Assert.AreEqual("l0", project.GetItems("l").First().GetMetadataValue("l")); Assert.AreEqual("m1", project.GetItems("l").First().GetMetadataValue("m")); Assert.AreEqual("n1", project.GetItems("l").First().GetMetadataValue("n")); Assert.AreEqual("o2", project.GetItems("l").First().GetMetadataValue("o")); Assert.AreEqual("p4", project.GetItems("l").First().GetMetadataValue("p")); Assert.AreEqual("", project.GetItems("l").ElementAt(1).GetMetadataValue("l")); Assert.AreEqual("", project.GetItems("l").ElementAt(1).GetMetadataValue("m")); Assert.AreEqual("", project.GetItems("l").ElementAt(1).GetMetadataValue("n")); Assert.AreEqual("", project.GetItems("l").ElementAt(1).GetMetadataValue("o")); Assert.AreEqual("", project.GetItems("l").ElementAt(1).GetMetadataValue("p")); Assert.AreEqual("l0", project.GetItems("m").First().GetMetadataValue("l")); Assert.AreEqual("m1", project.GetItems("m").First().GetMetadataValue("m")); Assert.AreEqual("n1", project.GetItems("m").First().GetMetadataValue("n")); Assert.AreEqual("o4", project.GetItems("m").First().GetMetadataValue("o")); Assert.AreEqual("p4", project.GetItems("m").First().GetMetadataValue("p")); Assert.AreEqual("", project.GetItems("m").ElementAt(1).GetMetadataValue("l")); Assert.AreEqual("", project.GetItems("m").ElementAt(1).GetMetadataValue("m")); Assert.AreEqual("", project.GetItems("m").ElementAt(1).GetMetadataValue("n")); Assert.AreEqual("o4", project.GetItems("m").ElementAt(1).GetMetadataValue("o")); Assert.AreEqual("", project.GetItems("m").ElementAt(1).GetMetadataValue("p")); // Should still point at the same XML metadata Assert.AreEqual(true, Object.ReferenceEquals(project.GetItems("i").First().GetMetadata("l").Xml, project.GetItems("m").First().GetMetadata("l").Xml)); Assert.AreEqual(true, Object.ReferenceEquals(project.GetItems("i").First().GetMetadata("m").Xml, project.GetItems("m").First().GetMetadata("m").Xml)); Assert.AreEqual(true, Object.ReferenceEquals(project.GetItems("i").First().GetMetadata("n").Xml, project.GetItems("m").First().GetMetadata("n").Xml)); Assert.AreEqual(true, Object.ReferenceEquals(project.GetItems("j").First().GetMetadata("o").Xml, project.GetItems("k").First().GetMetadata("o").Xml)); Assert.AreEqual(true, Object.ReferenceEquals(project.GetItems("k").First().GetMetadata("p").Xml, project.GetItems("m").First().GetMetadata("p").Xml)); Assert.AreEqual(true, !Object.ReferenceEquals(project.GetItems("j").First().GetMetadata("p").Xml, project.GetItems("m").First().GetMetadata("p").Xml)); } /// <summary> /// Metadata on items can refer to metadata above /// </summary> [TestMethod] public void MetadataReferringToMetadataAbove() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m1>v1</m1> <m2>%(m1);v2;%(m0)</m2> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); var itemMetadata = Helpers.MakeList(item.Metadata); Assert.AreEqual(2, itemMetadata.Count); Assert.AreEqual("v1;v2;", item.GetMetadataValue("m2")); } /// <summary> /// Built-in metadata should work, too. /// NOTE: To work properly, this should batch. This is a temporary "patch" to make it work for now. /// It will only give correct results if there is exactly one item in the Include. Otherwise Batching would be needed. /// </summary> [TestMethod] public void BuiltInMetadataExpression() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m>%(Identity)</m> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); Assert.AreEqual("i1", item.GetMetadataValue("m")); } /// <summary> /// Qualified built in metadata should work /// </summary> [TestMethod] public void BuiltInQualifiedMetadataExpression() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m>%(i.Identity)</m> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); Assert.AreEqual("i1", item.GetMetadataValue("m")); } /// <summary> /// Mis-qualified built in metadata should not work /// </summary> [TestMethod] public void BuiltInMisqualifiedMetadataExpression() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m>%(j.Identity)</m> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); Assert.AreEqual(String.Empty, item.GetMetadataValue("m")); } /// <summary> /// Metadata condition should work correctly with built-in metadata /// </summary> [TestMethod] public void BuiltInMetadataInMetadataCondition() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m Condition=""'%(Identity)'=='i1'"">m1</m> <n Condition=""'%(Identity)'=='i2'"">n1</n> </i> </ItemGroup> </Project> "; ProjectItem item = GetOneItem(content); Assert.AreEqual("m1", item.GetMetadataValue("m")); Assert.AreEqual(String.Empty, item.GetMetadataValue("n")); } /// <summary> /// Metadata on item condition not allowed (currently) /// </summary> [TestMethod] [ExpectedException(typeof(InvalidProjectFileException))] public void BuiltInMetadataInItemCondition() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1' Condition=""'%(Identity)'=='i1'/> </ItemGroup> </Project> "; GetOneItem(content); } /// <summary> /// Two items should each get their own values for built-in metadata /// </summary> [TestMethod] public void BuiltInMetadataTwoItems() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1.cpp;c:\bar\i2.cpp'> <m>%(Filename).obj</m> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = GetItems(content); Assert.AreEqual(@"i1.obj", items[0].GetMetadataValue("m")); Assert.AreEqual(@"i2.obj", items[1].GetMetadataValue("m")); } /// <summary> /// Items from another list, but with different metadata /// </summary> [TestMethod] public void DifferentMetadataItemsFromOtherList() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0'> <m>m1</m> </h> <h Include='h1'/> <i Include='@(h)'> <m>%(m)</m> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = GetItems(content); Assert.AreEqual(@"m1", items[0].GetMetadataValue("m")); Assert.AreEqual(String.Empty, items[1].GetMetadataValue("m")); } /// <summary> /// Items from another list, but with different metadata /// </summary> [TestMethod] public void DifferentBuiltInMetadataItemsFromOtherList() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0.x'/> <h Include='h1.y'/> <i Include='@(h)'> <m>%(extension)</m> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = GetItems(content); Assert.AreEqual(@".x", items[0].GetMetadataValue("m")); Assert.AreEqual(@".y", items[1].GetMetadataValue("m")); } /// <summary> /// Two items coming from a transform /// </summary> [TestMethod] public void BuiltInMetadataTransformInInclude() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0'/> <h Include='h1'/> <i Include=""@(h->'%(Identity).baz')""> <m>%(Filename)%(Extension).obj</m> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = GetItems(content); Assert.AreEqual(@"h0.baz.obj", items[0].GetMetadataValue("m")); Assert.AreEqual(@"h1.baz.obj", items[1].GetMetadataValue("m")); } /// <summary> /// Transform in the metadata value; no bare metadata involved /// </summary> [TestMethod] public void BuiltInMetadataTransformInMetadataValue() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0'/> <h Include='h1'/> <i Include='i0'/> <i Include='i1;i2'> <m>@(i);@(h->'%(Filename)')</m> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = GetItems(content); Assert.AreEqual(@"i0;h0;h1", items[1].GetMetadataValue("m")); Assert.AreEqual(@"i0;h0;h1", items[2].GetMetadataValue("m")); } /// <summary> /// Transform in the metadata value; bare metadata involved /// </summary> [TestMethod] public void BuiltInMetadataTransformInMetadataValueBareMetadataPresent() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0'/> <h Include='h1'/> <i Include='i0.x'/> <i Include='i1.y;i2'> <m>@(i);@(h->'%(Filename)');%(Extension)</m> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = GetItems(content); Assert.AreEqual(@"i0.x;h0;h1;.y", items[1].GetMetadataValue("m")); Assert.AreEqual(@"i0.x;h0;h1;", items[2].GetMetadataValue("m")); } /// <summary> /// Metadata on items can refer to item lists /// </summary> [TestMethod] public void MetadataValueReferringToItems() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0'/> <i Include='i0'/> <i Include='i1'> <m1>@(h);@(i)</m1> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = GetItems(content); Assert.AreEqual("h0;i0", items[1].GetMetadataValue("m1")); } /// <summary> /// Metadata on items' conditions can refer to item lists /// </summary> [TestMethod] public void MetadataConditionReferringToItems() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <h Include='h0'/> <i Include='i0'/> <i Include='i1'> <m1 Condition=""'@(h)'=='h0' and '@(i)'=='i0'"">v1</m1> <m2 Condition=""'@(h)'!='h0' or '@(i)'!='i0'"">v2</m2> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = GetItems(content); Assert.AreEqual("v1", items[1].GetMetadataValue("m1")); Assert.AreEqual(String.Empty, items[1].GetMetadataValue("m2")); } /// <summary> /// Metadata on items' conditions can refer to other metadata /// </summary> [TestMethod] public void MetadataConditionReferringToMetadataOnSameItem() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m0>0</m0> <m1 Condition=""'%(m0)'=='0'"">1</m1> <m2 Condition=""'%(m0)'=='3'"">2</m2> </i> </ItemGroup> </Project> "; IList<ProjectItem> items = GetItems(content); Assert.AreEqual("0", items[0].GetMetadataValue("m0")); Assert.AreEqual("1", items[0].GetMetadataValue("m1")); Assert.AreEqual(String.Empty, items[0].GetMetadataValue("m2")); } /// <summary> /// Remove a metadatum /// </summary> [TestMethod] public void RemoveMetadata() { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; item.SetMetadataValue("m", "m1"); project.ReevaluateIfNecessary(); bool found = item.RemoveMetadata("m"); Assert.AreEqual(true, found); Assert.AreEqual(true, project.IsDirty); Assert.AreEqual(String.Empty, item.GetMetadataValue("m")); Assert.AreEqual(0, Helpers.Count(item.Xml.Metadata)); } /// <summary> /// Attempt to remove a metadatum originating from an item definition. /// Should fail if it was not overridden. /// </summary> [TestMethod] public void RemoveItemDefinitionMetadataMasked() { ProjectRootElement xml = ProjectRootElement.Create(); xml.AddItemDefinition("i").AddMetadata("m", "m1"); xml.AddItem("i", "i1").AddMetadata("m", "m2"); Project project = new Project(xml); ProjectItem item = Helpers.GetFirst(project.GetItems("i")); bool found = item.RemoveMetadata("m"); Assert.AreEqual(true, found); Assert.AreEqual(0, item.DirectMetadataCount); Assert.AreEqual(0, Helpers.Count(item.DirectMetadata)); Assert.AreEqual("m1", item.GetMetadataValue("m")); // Now originating from definition! Assert.AreEqual(true, project.IsDirty); Assert.AreEqual(0, item.Xml.Count); } /// <summary> /// Attempt to remove a metadatum originating from an item definition. /// Should fail if it was not overridden. /// </summary> [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void RemoveItemDefinitionMetadataNotMasked() { ProjectRootElement xml = ProjectRootElement.Create(); xml.AddItemDefinition("i").AddMetadata("m", "m1"); xml.AddItem("i", "i1"); Project project = new Project(xml); ProjectItem item = Helpers.GetFirst(project.GetItems("i")); item.RemoveMetadata("m"); // Should throw } /// <summary> /// Remove a nonexistent metadatum /// </summary> [TestMethod] public void RemoveNonexistentMetadata() { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; project.ReevaluateIfNecessary(); bool found = item.RemoveMetadata("m"); Assert.AreEqual(false, found); Assert.AreEqual(false, project.IsDirty); } /// <summary> /// Tests removing built-in metadata. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentException))] public void RemoveBuiltInMetadata() { ProjectRootElement xml = ProjectRootElement.Create(); xml.AddItem("i", "i1"); Project project = new Project(xml); ProjectItem item = Helpers.GetFirst(project.GetItems("i")); // This should throw item.RemoveMetadata("FullPath"); } /// <summary> /// Simple rename /// </summary> [TestMethod] public void Rename() { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; project.ReevaluateIfNecessary(); // populate built in metadata cache for this item, to verify the cache is cleared out by the rename Assert.AreEqual("i1", item.GetMetadataValue("FileName")); item.Rename("i2"); Assert.AreEqual("i2", item.Xml.Include); Assert.AreEqual("i2", item.EvaluatedInclude); Assert.AreEqual(true, project.IsDirty); Assert.AreEqual("i2", item.GetMetadataValue("FileName")); } /// <summary> /// Verifies that renaming a ProjectItem whose xml backing is a wildcard doesn't corrupt /// the MSBuild evaluation data. /// </summary> [TestMethod] public void RenameItemInProjectWithWildcards() { string projectDirectory = Path.Combine(this.TestContext.TestRunDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(projectDirectory); try { string sourceFile = Path.Combine(projectDirectory, "a.cs"); string renamedSourceFile = Path.Combine(projectDirectory, "b.cs"); File.Create(sourceFile).Dispose(); var project = new Project(); project.AddItem("File", "*.cs"); project.FullPath = Path.Combine(projectDirectory, "test.proj"); // assign a path so the wildcards can lock onto something. project.ReevaluateIfNecessary(); var projectItem = project.Items.Single(); Assert.AreEqual(Path.GetFileName(sourceFile), projectItem.EvaluatedInclude); Assert.AreSame(projectItem, project.GetItemsByEvaluatedInclude(projectItem.EvaluatedInclude).Single()); projectItem.Rename(Path.GetFileName(renamedSourceFile)); File.Move(sourceFile, renamedSourceFile); // repro w/ or w/o this project.ReevaluateIfNecessary(); projectItem = project.Items.Single(); Assert.AreEqual(Path.GetFileName(renamedSourceFile), projectItem.EvaluatedInclude); Assert.AreSame(projectItem, project.GetItemsByEvaluatedInclude(projectItem.EvaluatedInclude).Single()); } finally { Directory.Delete(projectDirectory, recursive: true); } } /// <summary> /// Change item type /// </summary> [TestMethod] public void ChangeItemType() { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; project.ReevaluateIfNecessary(); item.ItemType = "j"; Assert.AreEqual("j", item.ItemType); Assert.AreEqual(true, project.IsDirty); } /// <summary> /// Change item type to invalid value /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentException))] public void ChangeItemTypeInvalid() { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; project.ReevaluateIfNecessary(); item.ItemType = "|"; } /// <summary> /// Attempt to rename imported item should fail /// </summary> [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void RenameImported() { string file = null; try { file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); Project import = new Project(); import.AddItem("i", "i1"); import.Save(file); ProjectRootElement xml = ProjectRootElement.Create(); xml.AddImport(file); Project project = new Project(xml); ProjectItem item = Helpers.GetFirst(project.GetItems("i")); item.Rename("i2"); } finally { File.Delete(file); } } /// <summary> /// Attempt to set metadata on imported item should fail /// </summary> [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void SetMetadataImported() { string file = null; try { file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); Project import = new Project(); import.AddItem("i", "i1"); import.Save(file); ProjectRootElement xml = ProjectRootElement.Create(); xml.AddImport(file); Project project = new Project(xml); ProjectItem item = Helpers.GetFirst(project.GetItems("i")); item.SetMetadataValue("m", "m0"); } finally { File.Delete(file); } } /// <summary> /// Attempt to remove metadata on imported item should fail /// </summary> [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void RemoveMetadataImported() { string file = null; try { file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile(); Project import = new Project(); ProjectItem item = import.AddItem("i", "i1")[0]; item.SetMetadataValue("m", "m0"); import.Save(file); ProjectRootElement xml = ProjectRootElement.Create(); xml.AddImport(file); Project project = new Project(xml); item = Helpers.GetFirst(project.GetItems("i")); item.RemoveMetadata("m"); } finally { File.Delete(file); } } /// <summary> /// Get items of item type "i" with using the item xml fragment passed in /// </summary> private static IList<ProjectItem> GetItemsFromFragment(string fragment) { string content = String.Format ( @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> {0} </ItemGroup> </Project> ", fragment ); IList<ProjectItem> items = GetItems(content); return items; } /// <summary> /// Get the item of type "i" using the item Xml fragment provided. /// If there is more than one, fail. /// </summary> private static ProjectItem GetOneItemFromFragment(string fragment) { IList<ProjectItem> items = GetItemsFromFragment(fragment); Assert.AreEqual(1, items.Count); return items[0]; } /// <summary> /// Get the items of type "i" in the project provided /// </summary> private static IList<ProjectItem> GetItems(string content) { ProjectRootElement projectXml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Project project = new Project(projectXml); IList<ProjectItem> item = Helpers.MakeList(project.GetItems("i")); return item; } /// <summary> /// Get the item of type "i" in the project provided. /// If there is more than one, fail. /// </summary> private static ProjectItem GetOneItem(string content) { IList<ProjectItem> items = GetItems(content); Assert.AreEqual(1, items.Count); return items[0]; } /// <summary> /// Asserts that the list of items has the specified includes. /// </summary> private static void AssertEvaluatedIncludes(IList<ProjectItem> items, string[] includes) { for (int i = 0; i < includes.Length; i++) { Assert.AreEqual(includes[i], items[i].EvaluatedInclude); } } } }
using System; using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using Abp.Collections.Extensions; namespace Abp.Extensions { /// <summary> /// Extension methods for String class. /// </summary> public static class StringExtensions { /// <summary> /// Adds a char to end of given string if it does not ends with the char. /// </summary> public static string EnsureEndsWith(this string str, char c) { return EnsureEndsWith(str, c, StringComparison.InvariantCulture); } /// <summary> /// Adds a char to end of given string if it does not ends with the char. /// </summary> public static string EnsureEndsWith(this string str, char c, StringComparison comparisonType) { if (str == null) { throw new ArgumentNullException("str"); } if (str.EndsWith(c.ToString(CultureInfo.InvariantCulture), comparisonType)) { return str; } return str + c; } /// <summary> /// Adds a char to end of given string if it does not ends with the char. /// </summary> public static string EnsureEndsWith(this string str, char c, bool ignoreCase, CultureInfo culture) { if (str == null) { throw new ArgumentNullException("str"); } if (str.EndsWith(c.ToString(culture), ignoreCase, culture)) { return str; } return str + c; } /// <summary> /// Adds a char to beginning of given string if it does not starts with the char. /// </summary> public static string EnsureStartsWith(this string str, char c) { return EnsureStartsWith(str, c, StringComparison.InvariantCulture); } /// <summary> /// Adds a char to beginning of given string if it does not starts with the char. /// </summary> public static string EnsureStartsWith(this string str, char c, StringComparison comparisonType) { if (str == null) { throw new ArgumentNullException("str"); } if (str.StartsWith(c.ToString(CultureInfo.InvariantCulture), comparisonType)) { return str; } return c + str; } /// <summary> /// Adds a char to beginning of given string if it does not starts with the char. /// </summary> public static string EnsureStartsWith(this string str, char c, bool ignoreCase, CultureInfo culture) { if (str == null) { throw new ArgumentNullException("str"); } if (str.StartsWith(c.ToString(culture), ignoreCase, culture)) { return str; } return c + str; } /// <summary> /// Indicates whether this string is null or an System.String.Empty string. /// </summary> public static bool IsNullOrEmpty(this string str) { return string.IsNullOrEmpty(str); } /// <summary> /// indicates whether this string is null, empty, or consists only of white-space characters. /// </summary> public static bool IsNullOrWhiteSpace(this string str) { return string.IsNullOrWhiteSpace(str); } /// <summary> /// Gets a substring of a string from beginning of the string. /// </summary> /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception> public static string Left(this string str, int len) { if (str == null) { throw new ArgumentNullException("str"); } if (str.Length < len) { throw new ArgumentException("len argument can not be bigger than given string's length!"); } return str.Substring(0, len); } /// <summary> /// Converts line endings in the string to <see cref="Environment.NewLine"/>. /// </summary> public static string NormalizeLineEndings(this string str) { return str.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", Environment.NewLine); } /// <summary> /// Gets index of nth occurence of a char in a string. /// </summary> /// <param name="str">source string to be searched</param> /// <param name="c">Char to search in <see cref="str"/></param> /// <param name="n">Count of the occurence</param> public static int NthIndexOf(this string str, char c, int n) { if (str == null) { throw new ArgumentNullException(nameof(str)); } var count = 0; for (var i = 0; i < str.Length; i++) { if (str[i] != c) { continue; } if ((++count) == n) { return i; } } return -1; } /// <summary> /// Removes first occurrence of the given postfixes from end of the given string. /// </summary> /// <param name="str">The string.</param> /// <param name="postFixes">one or more postfix.</param> /// <returns>Modified string or the same string if it has not any of given postfixes</returns> public static string RemovePostFix(this string str, params string[] postFixes) { if (str.IsNullOrEmpty()) { return null; } if (postFixes.IsNullOrEmpty()) { return str; } foreach (var postFix in postFixes) { if (str.EndsWith(postFix)) { return str.Left(str.Length - postFix.Length); } } return str; } /// <summary> /// Removes first occurrence of the given prefixes from beginning of the given string. /// </summary> /// <param name="str">The string.</param> /// <param name="preFixes">one or more prefix.</param> /// <returns>Modified string or the same string if it has not any of given prefixes</returns> public static string RemovePreFix(this string str, params string[] preFixes) { if (str.IsNullOrEmpty()) { return null; } if (preFixes.IsNullOrEmpty()) { return str; } foreach (var preFix in preFixes) { if (str.StartsWith(preFix)) { return str.Right(str.Length - preFix.Length); } } return str; } /// <summary> /// Gets a substring of a string from end of the string. /// </summary> /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception> public static string Right(this string str, int len) { if (str == null) { throw new ArgumentNullException("str"); } if (str.Length < len) { throw new ArgumentException("len argument can not be bigger than given string's length!"); } return str.Substring(str.Length - len, len); } /// <summary> /// Uses string.Split method to split given string by given separator. /// </summary> public static string[] Split(this string str, string separator) { return str.Split(new[] { separator }, StringSplitOptions.None); } /// <summary> /// Uses string.Split method to split given string by given separator. /// </summary> public static string[] Split(this string str, string separator, StringSplitOptions options) { return str.Split(new[] { separator }, options); } /// <summary> /// Uses string.Split method to split given string by <see cref="Environment.NewLine"/>. /// </summary> public static string[] SplitToLines(this string str) { return str.Split(Environment.NewLine); } /// <summary> /// Uses string.Split method to split given string by <see cref="Environment.NewLine"/>. /// </summary> public static string[] SplitToLines(this string str, StringSplitOptions options) { return str.Split(Environment.NewLine, options); } /// <summary> /// Converts PascalCase string to camelCase string. /// </summary> /// <param name="str">String to convert</param> /// <returns>camelCase of the string</returns> public static string ToCamelCase(this string str) { return str.ToCamelCase(CultureInfo.InvariantCulture); } /// <summary> /// Converts PascalCase string to camelCase string in specified culture. /// </summary> /// <param name="str">String to convert</param> /// <param name="culture">An object that supplies culture-specific casing rules</param> /// <returns>camelCase of the string</returns> public static string ToCamelCase(this string str, CultureInfo culture) { if (string.IsNullOrWhiteSpace(str)) { return str; } if (str.Length == 1) { return str.ToLower(culture); } return char.ToLower(str[0], culture) + str.Substring(1); } /// <summary> /// Converts given PascalCase/camelCase string to sentence (by splitting words by space). /// Example: "ThisIsSampleSentence" is converted to "This is a sample sentence". /// </summary> /// <param name="str">String to convert.</param> public static string ToSentenceCase(this string str) { return str.ToSentenceCase(CultureInfo.InvariantCulture); } /// <summary> /// Converts given PascalCase/camelCase string to sentence (by splitting words by space). /// Example: "ThisIsSampleSentence" is converted to "This is a sample sentence". /// </summary> /// <param name="str">String to convert.</param> /// <param name="culture">An object that supplies culture-specific casing rules.</param> public static string ToSentenceCase(this string str, CultureInfo culture) { if (string.IsNullOrWhiteSpace(str)) { return str; } return Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + " " + char.ToLower(m.Value[1], culture)); } /// <summary> /// Converts string to enum value. /// </summary> /// <typeparam name="T">Type of enum</typeparam> /// <param name="value">String value to convert</param> /// <returns>Returns enum object</returns> public static T ToEnum<T>(this string value) where T : struct { if (value == null) { throw new ArgumentNullException("value"); } return (T)Enum.Parse(typeof(T), value); } /// <summary> /// Converts string to enum value. /// </summary> /// <typeparam name="T">Type of enum</typeparam> /// <param name="value">String value to convert</param> /// <param name="ignoreCase">Ignore case</param> /// <returns>Returns enum object</returns> public static T ToEnum<T>(this string value, bool ignoreCase) where T : struct { if (value == null) { throw new ArgumentNullException("value"); } return (T)Enum.Parse(typeof(T), value, ignoreCase); } public static string ToMd5(this string str) { using (var md5 = MD5.Create()) { var inputBytes = Encoding.UTF8.GetBytes(str); var hashBytes = md5.ComputeHash(inputBytes); var sb = new StringBuilder(); foreach (var hashByte in hashBytes) { sb.Append(hashByte.ToString("X2")); } return sb.ToString(); } } /// <summary> /// Converts camelCase string to PascalCase string. /// </summary> /// <param name="str">String to convert</param> /// <returns>PascalCase of the string</returns> public static string ToPascalCase(this string str) { return str.ToPascalCase(CultureInfo.InvariantCulture); } /// <summary> /// Converts camelCase string to PascalCase string in specified culture. /// </summary> /// <param name="str">String to convert</param> /// <param name="culture">An object that supplies culture-specific casing rules</param> /// <returns>PascalCase of the string</returns> public static string ToPascalCase(this string str, CultureInfo culture) { if (string.IsNullOrWhiteSpace(str)) { return str; } if (str.Length == 1) { return str.ToUpper(culture); } return char.ToUpper(str[0], culture) + str.Substring(1); } /// <summary> /// Gets a substring of a string from beginning of the string if it exceeds maximum length. /// </summary> /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception> public static string Truncate(this string str, int maxLength) { if (str == null) { return null; } if (str.Length <= maxLength) { return str; } return str.Left(maxLength); } /// <summary> /// Gets a substring of a string from beginning of the string if it exceeds maximum length. /// It adds a "..." postfix to end of the string if it's truncated. /// Returning string can not be longer than maxLength. /// </summary> /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception> public static string TruncateWithPostfix(this string str, int maxLength) { return TruncateWithPostfix(str, maxLength, "..."); } /// <summary> /// Gets a substring of a string from beginning of the string if it exceeds maximum length. /// It adds given <paramref name="postfix"/> to end of the string if it's truncated. /// Returning string can not be longer than maxLength. /// </summary> /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception> public static string TruncateWithPostfix(this string str, int maxLength, string postfix) { if (str == null) { return null; } if (str == string.Empty || maxLength == 0) { return string.Empty; } if (str.Length <= maxLength) { return str; } if (maxLength <= postfix.Length) { return postfix.Left(maxLength); } return str.Left(maxLength - postfix.Length) + postfix; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using ASP.NETSinglePageApplication.Areas.HelpPage.ModelDescriptions; using ASP.NETSinglePageApplication.Areas.HelpPage.Models; namespace ASP.NETSinglePageApplication.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Linq; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal enum MemLookFlags : uint { None = 0, Ctor = EXPRFLAG.EXF_CTOR, NewObj = EXPRFLAG.EXF_NEWOBJCALL, Operator = EXPRFLAG.EXF_OPERATOR, Indexer = EXPRFLAG.EXF_INDEXER, UserCallable = EXPRFLAG.EXF_USERCALLABLE, BaseCall = EXPRFLAG.EXF_BASECALL, // All EXF flags are < 0x01000000 MustBeInvocable = 0x20000000, TypeVarsAllowed = 0x40000000, ExtensionCall = 0x80000000, All = Ctor | NewObj | Operator | Indexer | UserCallable | BaseCall | MustBeInvocable | TypeVarsAllowed | ExtensionCall } ///////////////////////////////////////////////////////////////////////////////// // MemberLookup class handles looking for a member within a type and its // base types. This only handles AGGTYPESYMs and TYVARSYMs. // // Lookup must be called before any other methods. internal class MemberLookup { // The inputs to Lookup. private CSemanticChecker _pSemanticChecker; private SymbolLoader _pSymbolLoader; private CType _typeSrc; private EXPR _obj; private CType _typeQual; private ParentSymbol _symWhere; private Name _name; private int _arity; private MemLookFlags _flags; private CMemberLookupResults _results; // For maintaining the type array. We throw the first 8 or so here. private List<AggregateType> _rgtypeStart; // Results of the lookup. private List<AggregateType> _prgtype; private int _csym; // Number of syms found. private SymWithType _swtFirst; // The first symbol found. private List<MethPropWithType> _methPropWithTypeList; // When we look up methods, we want to keep the list of all candidate methods given a particular name. // These are for error reporting. private SymWithType _swtAmbig; // An ambiguous symbol. private SymWithType _swtInaccess; // An inaccessible symbol. private SymWithType _swtBad; // If we're looking for a ructor or indexer, this matched on name, but isn't the right thing. private SymWithType _swtBogus; // A bogus member - such as an indexed property. private SymWithType _swtBadArity; // An symbol with the wrong arity. private SymWithType _swtAmbigWarn; // An ambiguous symbol, but only warn. // We have an override symbol, which we've errored on in SymbolPrepare. If we have nothing better, use this. // This is because if we have: // // class C : D // { // public override int M() { } // static void Main() // { // C c = new C(); // c.M(); <-- // // We try to look up M, and find the M on C, but throw it out since its an override, and // we want the virtual that it overrides. However, in this case, we'll never find that // virtual, since it doesn't exist. We therefore want to use the override anyway, and // continue on to give results with that. private SymWithType _swtOverride; private bool _fMulti; // Whether symFirst is of a kind for which we collect multiples (methods and indexers). /*************************************************************************************************** Another match was found. Increment the count of syms and add the type to our list if it's not already there. ***************************************************************************************************/ private void RecordType(AggregateType type, Symbol sym) { Debug.Assert(type != null && sym != null); if (!_prgtype.Contains(type)) { _prgtype.Add(type); } // Now record the sym.... _csym++; // If it is first, record it. if (_swtFirst == null) { _swtFirst.Set(sym, type); Debug.Assert(_csym == 1); Debug.Assert(_prgtype[0] == type); _fMulti = sym.IsMethodSymbol() || sym.IsPropertySymbol() && sym.AsPropertySymbol().isIndexer(); } } /****************************************************************************** Search just the given type (not any bases). Returns true iff it finds something (which will have been recorded by RecordType). pfHideByName is set to true iff something was found that hides all members of base types (eg, a hidebyname method). ******************************************************************************/ private bool SearchSingleType(AggregateType typeCur, out bool pfHideByName) { bool fFoundSome = false; MethPropWithType mwpInsert; pfHideByName = false; // Make sure this type is accessible. It may not be due to private inheritance // or friend assemblies. bool fInaccess = !GetSemanticChecker().CheckTypeAccess(typeCur, _symWhere); if (fInaccess && (_csym != 0 || _swtInaccess != null)) return false; // Loop through symbols. Symbol symCur = null; for (symCur = GetSymbolLoader().LookupAggMember(_name, typeCur.getAggregate(), symbmask_t.MASK_ALL); symCur != null; symCur = GetSymbolLoader().LookupNextSym(symCur, typeCur.getAggregate(), symbmask_t.MASK_ALL)) { // Check for arity. switch (symCur.getKind()) { case SYMKIND.SK_MethodSymbol: // For non-zero arity, only methods of the correct arity are considered. // For zero arity, don't filter out any methods since we do type argument // inferencing. if (_arity > 0 && symCur.AsMethodSymbol().typeVars.size != _arity) { if (!_swtBadArity) _swtBadArity.Set(symCur, typeCur); continue; } break; case SYMKIND.SK_AggregateSymbol: // For types, always filter on arity. if (symCur.AsAggregateSymbol().GetTypeVars().size != _arity) { if (!_swtBadArity) _swtBadArity.Set(symCur, typeCur); continue; } break; case SYMKIND.SK_TypeParameterSymbol: if ((_flags & MemLookFlags.TypeVarsAllowed) == 0) continue; if (_arity > 0) { if (!_swtBadArity) _swtBadArity.Set(symCur, typeCur); continue; } break; default: // All others are only considered when arity is zero. if (_arity > 0) { if (!_swtBadArity) _swtBadArity.Set(symCur, typeCur); continue; } break; } // Check for user callability. if (symCur.IsOverride() && !symCur.IsHideByName()) { if (!_swtOverride) { _swtOverride.Set(symCur, typeCur); } continue; } if ((_flags & MemLookFlags.UserCallable) != 0 && symCur.IsMethodOrPropertySymbol() && !symCur.AsMethodOrPropertySymbol().isUserCallable()) { bool bIsIndexedProperty = false; // If its an indexed property method symbol, let it through. if (symCur.IsMethodSymbol() && symCur.AsMethodSymbol().isPropertyAccessor() && ((symCur.name.Text.StartsWith("set_", StringComparison.Ordinal) && symCur.AsMethodSymbol().Params.size > 1) || (symCur.name.Text.StartsWith("get_", StringComparison.Ordinal) && symCur.AsMethodSymbol().Params.size > 0))) { bIsIndexedProperty = true; } if (!bIsIndexedProperty) { if (!_swtInaccess) { _swtInaccess.Set(symCur, typeCur); } continue; } } if (fInaccess || !GetSemanticChecker().CheckAccess(symCur, typeCur, _symWhere, _typeQual)) { // Not accessible so get the next sym. if (!_swtInaccess) { _swtInaccess.Set(symCur, typeCur); } if (fInaccess) { return false; } continue; } // Make sure that whether we're seeing a ctor, operator, or indexer is consistent with the flags. if (((_flags & MemLookFlags.Ctor) == 0) != (!symCur.IsMethodSymbol() || !symCur.AsMethodSymbol().IsConstructor()) || ((_flags & MemLookFlags.Operator) == 0) != (!symCur.IsMethodSymbol() || !symCur.AsMethodSymbol().isOperator) || ((_flags & MemLookFlags.Indexer) == 0) != (!symCur.IsPropertySymbol() || !symCur.AsPropertySymbol().isIndexer())) { if (!_swtBad) { _swtBad.Set(symCur, typeCur); } continue; } // We can't call CheckBogus on methods or indexers because if the method has the wrong // number of parameters people don't think they should have to /r the assemblies containing // the parameter types and they complain about the resulting CS0012 errors. if (!symCur.IsMethodSymbol() && (_flags & MemLookFlags.Indexer) == 0 && GetSemanticChecker().CheckBogus(symCur)) { // A bogus member - we can't use these, so only record them for error reporting. if (!_swtBogus) { _swtBogus.Set(symCur, typeCur); } continue; } // if we are in a calling context then we should only find a property if it is delegate valued if ((_flags & MemLookFlags.MustBeInvocable) != 0) { if ((symCur.IsFieldSymbol() && !IsDelegateType(symCur.AsFieldSymbol().GetType(), typeCur) && !IsDynamicMember(symCur)) || (symCur.IsPropertySymbol() && !IsDelegateType(symCur.AsPropertySymbol().RetType, typeCur) && !IsDynamicMember(symCur))) { if (!_swtBad) { _swtBad.Set(symCur, typeCur); } continue; } } if (symCur.IsMethodOrPropertySymbol()) { mwpInsert = new MethPropWithType(symCur.AsMethodOrPropertySymbol(), typeCur); _methPropWithTypeList.Add(mwpInsert); } // We have a visible symbol. fFoundSome = true; if (_swtFirst) { if (!typeCur.isInterfaceType()) { // Non-interface case. Debug.Assert(_fMulti || typeCur == _prgtype[0]); if (!_fMulti) { if (_swtFirst.Sym.IsFieldSymbol() && symCur.IsEventSymbol() #if !CSEE // The isEvent bit is only set on symbols which come from source... // This is not a problem for the compiler because the field is only // accessible in the scope in whcih it is declared, // but in the EE we ignore accessibility... && _swtFirst.Field().isEvent #endif ) { // m_swtFirst is just the field behind the event symCur so ignore symCur. continue; } else if (_swtFirst.Sym.IsFieldSymbol() && symCur.IsEventSymbol()) { // symCur is the matching event. continue; } goto LAmbig; } if (_swtFirst.Sym.getKind() != symCur.getKind()) { if (typeCur == _prgtype[0]) goto LAmbig; // This one is hidden by the first one. This one also hides any more in base types. pfHideByName = true; continue; } } // Interface case. // m_fMulti : n n n y y y y y // same-kind : * * * y n n n n // fDiffHidden: * * * * y n n n // meth : * * * * * y n * can n happen? just in case, we better handle it.... // hack : n * y * * y * n // meth-2 : * n y * * * * * // res : A A S R H H A A else if (!_fMulti) { // Give method groups priority. if ( /* !GetSymbolLoader().options.fLookupHack ||*/ !symCur.IsMethodSymbol()) goto LAmbig; _swtAmbigWarn = _swtFirst; // Erase previous results so we'll record this method as the first. _prgtype = new List<AggregateType>(); _csym = 0; _swtFirst.Clear(); _swtAmbig.Clear(); } else if (_swtFirst.Sym.getKind() != symCur.getKind()) { if (!typeCur.fDiffHidden) { // Give method groups priority. if ( /*!GetSymbolLoader().options.fLookupHack ||*/ !_swtFirst.Sym.IsMethodSymbol()) goto LAmbig; if (!_swtAmbigWarn) _swtAmbigWarn.Set(symCur, typeCur); } // This one is hidden by another. This one also hides any more in base types. pfHideByName = true; continue; } } RecordType(typeCur, symCur); if (symCur.IsMethodOrPropertySymbol() && symCur.AsMethodOrPropertySymbol().isHideByName) pfHideByName = true; // We've found a symbol in this type but need to make sure there aren't any conflicting // syms here, so keep searching the type. } Debug.Assert(!fInaccess || !fFoundSome); return fFoundSome; LAmbig: // Ambiguous! if (!_swtAmbig) _swtAmbig.Set(symCur, typeCur); pfHideByName = true; return true; } private bool IsDynamicMember(Symbol sym) { System.Runtime.CompilerServices.DynamicAttribute da = null; if (sym.IsFieldSymbol()) { if (!sym.AsFieldSymbol().getType().isPredefType(PredefinedType.PT_OBJECT)) { return false; } var o = sym.AsFieldSymbol().AssociatedFieldInfo.GetCustomAttributes(typeof(System.Runtime.CompilerServices.DynamicAttribute), false).ToArray(); if (o.Length == 1) { da = o[0] as System.Runtime.CompilerServices.DynamicAttribute; } } else { Debug.Assert(sym.IsPropertySymbol()); if (!sym.AsPropertySymbol().getType().isPredefType(PredefinedType.PT_OBJECT)) { return false; } var o = sym.AsPropertySymbol().AssociatedPropertyInfo.GetCustomAttributes(typeof(System.Runtime.CompilerServices.DynamicAttribute), false).ToArray(); if (o.Length == 1) { da = o[0] as System.Runtime.CompilerServices.DynamicAttribute; } } if (da == null) { return false; } return (da.TransformFlags.Count == 0 || (da.TransformFlags.Count == 1 && da.TransformFlags[0])); } /****************************************************************************** Lookup in a class and its bases (until *ptypeEnd is hit). ptypeEnd [in/out] - *ptypeEnd should be either null or object. If we find something here that would hide members of object, this sets *ptypeEnd to null. Returns true when searching should continue to the interfaces. ******************************************************************************/ private bool LookupInClass(AggregateType typeStart, ref AggregateType ptypeEnd) { Debug.Assert(!_swtFirst || _fMulti); Debug.Assert(typeStart != null && !typeStart.isInterfaceType() && (ptypeEnd == null || typeStart != ptypeEnd)); AggregateType typeEnd = ptypeEnd; AggregateType typeCur; // Loop through types. Loop until we hit typeEnd (object or null). for (typeCur = typeStart; typeCur != typeEnd && typeCur != null; typeCur = typeCur.GetBaseClass()) { Debug.Assert(!typeCur.isInterfaceType()); bool fHideByName = false; SearchSingleType(typeCur, out fHideByName); _flags &= ~MemLookFlags.TypeVarsAllowed; if (_swtFirst && !_fMulti) { // Everything below this type and in interfaces is hidden. return false; } if (fHideByName) { // This hides everything below it and in object, but not in the interfaces! ptypeEnd = null; // Return true to indicate that it's ok to search additional types. return true; } if ((_flags & MemLookFlags.Ctor) != 0) { // If we're looking for a constructor, don't check base classes or interfaces. return false; } } Debug.Assert(typeCur == typeEnd); return true; } /****************************************************************************** Returns true if searching should continue to object. ******************************************************************************/ private bool LookupInInterfaces(AggregateType typeStart, TypeArray types) { Debug.Assert(!_swtFirst || _fMulti); Debug.Assert(typeStart == null || typeStart.isInterfaceType()); Debug.Assert(typeStart != null || types.size != 0); // Clear all the hidden flags. Anything found in a class hides any other // kind of member in all the interfaces. if (typeStart != null) { typeStart.fAllHidden = false; typeStart.fDiffHidden = (_swtFirst != null); } for (int i = 0; i < types.size; i++) { AggregateType type = types.Item(i).AsAggregateType(); Debug.Assert(type.isInterfaceType()); type.fAllHidden = false; type.fDiffHidden = !!_swtFirst; } bool fHideObject = false; AggregateType typeCur = typeStart; int itypeNext = 0; if (typeCur == null) { typeCur = types.Item(itypeNext++).AsAggregateType(); } Debug.Assert(typeCur != null); // Loop through the interfaces. for (; ;) { Debug.Assert(typeCur != null && typeCur.isInterfaceType()); bool fHideByName = false; if (!typeCur.fAllHidden && SearchSingleType(typeCur, out fHideByName)) { fHideByName |= !_fMulti; // Mark base interfaces appropriately. TypeArray ifaces = typeCur.GetIfacesAll(); for (int i = 0; i < ifaces.size; i++) { AggregateType type = ifaces.Item(i).AsAggregateType(); Debug.Assert(type.isInterfaceType()); if (fHideByName) type.fAllHidden = true; type.fDiffHidden = true; } // If we hide all base types, that includes object! if (fHideByName) fHideObject = true; } _flags &= ~MemLookFlags.TypeVarsAllowed; if (itypeNext >= types.size) return !fHideObject; // Substitution has already been done. typeCur = types.Item(itypeNext++).AsAggregateType(); } } private SymbolLoader GetSymbolLoader() { return _pSymbolLoader; } private CSemanticChecker GetSemanticChecker() { return _pSemanticChecker; } private ErrorHandling GetErrorContext() { return GetSymbolLoader().GetErrorContext(); } private void ReportBogus(SymWithType swt) { Debug.Assert(swt.Sym.hasBogus() && swt.Sym.checkBogus()); MethodSymbol meth1; MethodSymbol meth2; switch (swt.Sym.getKind()) { case SYMKIND.SK_EventSymbol: break; case SYMKIND.SK_PropertySymbol: if (swt.Prop().useMethInstead) { meth1 = swt.Prop().methGet; meth2 = swt.Prop().methSet; ReportBogusForEventsAndProperties(swt, meth1, meth2); return; } break; case SYMKIND.SK_MethodSymbol: if (swt.Meth().name == GetSymbolLoader().GetNameManager().GetPredefName(PredefinedName.PN_INVOKE) && swt.Meth().getClass().IsDelegate()) { swt.Set(swt.Meth().getClass(), swt.GetType()); } break; default: break; } // Generic bogus error. GetErrorContext().ErrorRef(ErrorCode.ERR_BindToBogus, swt); } private void ReportBogusForEventsAndProperties(SymWithType swt, MethodSymbol meth1, MethodSymbol meth2) { if (meth1 != null && meth2 != null) { GetErrorContext().Error(ErrorCode.ERR_BindToBogusProp2, swt.Sym.name, new SymWithType(meth1, swt.GetType()), new SymWithType(meth2, swt.GetType()), new ErrArgRefOnly(swt.Sym)); return; } if (meth1 != null || meth2 != null) { GetErrorContext().Error(ErrorCode.ERR_BindToBogusProp1, swt.Sym.name, new SymWithType(meth1 != null ? meth1 : meth2, swt.GetType()), new ErrArgRefOnly(swt.Sym)); return; } throw Error.InternalCompilerError(); } private bool IsDelegateType(CType pSrcType, AggregateType pAggType) { CType pInstantiatedType = GetSymbolLoader().GetTypeManager().SubstType(pSrcType, pAggType, pAggType.GetTypeArgsAll()); return pInstantiatedType.isDelegateType(); } ///////////////////////////////////////////////////////////////////////////////// // Public methods. public MemberLookup() { _methPropWithTypeList = new List<MethPropWithType>(); _rgtypeStart = new List<AggregateType>(); _swtFirst = new SymWithType(); _swtAmbig = new SymWithType(); _swtInaccess = new SymWithType(); _swtBad = new SymWithType(); _swtBogus = new SymWithType(); _swtBadArity = new SymWithType(); _swtAmbigWarn = new SymWithType(); _swtOverride = new SymWithType(); } /*************************************************************************************************** Lookup must be called before anything else can be called. typeSrc - Must be an AggregateType or TypeParameterType. obj - the expression through which the member is being accessed. This is used for accessibility of protected members and for constructing a MEMGRP from the results of the lookup. It is legal for obj to be an EK_CLASS, in which case it may be used for accessibility, but will not be used for MEMGRP construction. symWhere - the symbol from with the name is being accessed (for checking accessibility). name - the name to look for. arity - the number of type args specified. Only members that support this arity are found. Note that when arity is zero, all methods are considered since we do type argument inferencing. flags - See MemLookFlags. TypeVarsAllowed only applies to the most derived type (not base types). ***************************************************************************************************/ public bool Lookup(CSemanticChecker checker, CType typeSrc, EXPR obj, ParentSymbol symWhere, Name name, int arity, MemLookFlags flags) { Debug.Assert((flags & ~MemLookFlags.All) == 0); Debug.Assert(obj == null || obj.type != null); Debug.Assert(typeSrc.IsAggregateType() || typeSrc.IsTypeParameterType()); Debug.Assert(checker != null); _prgtype = _rgtypeStart; // Save the inputs for error handling, etc. _pSemanticChecker = checker; _pSymbolLoader = checker.GetSymbolLoader(); _typeSrc = typeSrc; _obj = (obj != null && !obj.isCLASS()) ? obj : null; _symWhere = symWhere; _name = name; _arity = arity; _flags = flags; if ((_flags & MemLookFlags.BaseCall) != 0) _typeQual = null; else if ((_flags & MemLookFlags.Ctor) != 0) _typeQual = _typeSrc; else if (obj != null) _typeQual = (CType)obj.type; else _typeQual = null; // Determine what to search. AggregateType typeCls1 = null; AggregateType typeIface = null; TypeArray ifaces = BSYMMGR.EmptyTypeArray(); AggregateType typeCls2 = null; if (typeSrc.IsTypeParameterType()) { Debug.Assert((_flags & (MemLookFlags.Ctor | MemLookFlags.NewObj | MemLookFlags.Operator | MemLookFlags.BaseCall | MemLookFlags.TypeVarsAllowed)) == 0); _flags &= ~MemLookFlags.TypeVarsAllowed; ifaces = typeSrc.AsTypeParameterType().GetInterfaceBounds(); typeCls1 = typeSrc.AsTypeParameterType().GetEffectiveBaseClass(); if (ifaces.size > 0 && typeCls1.isPredefType(PredefinedType.PT_OBJECT)) typeCls1 = null; } else if (!typeSrc.isInterfaceType()) { typeCls1 = typeSrc.AsAggregateType(); if (typeCls1.IsWindowsRuntimeType()) { ifaces = typeCls1.GetWinRTCollectionIfacesAll(GetSymbolLoader()); } } else { Debug.Assert(typeSrc.isInterfaceType()); Debug.Assert((_flags & (MemLookFlags.Ctor | MemLookFlags.NewObj | MemLookFlags.Operator | MemLookFlags.BaseCall)) == 0); typeIface = typeSrc.AsAggregateType(); ifaces = typeIface.GetIfacesAll(); } if (typeIface != null || ifaces.size > 0) typeCls2 = GetSymbolLoader().GetReqPredefType(PredefinedType.PT_OBJECT); // Search the class first (except possibly object). if (typeCls1 == null || LookupInClass(typeCls1, ref typeCls2)) { // Search the interfaces. if ((typeIface != null || ifaces.size > 0) && LookupInInterfaces(typeIface, ifaces) && typeCls2 != null) { // Search object last. Debug.Assert(typeCls2 != null && typeCls2.isPredefType(PredefinedType.PT_OBJECT)); AggregateType result = null; LookupInClass(typeCls2, ref result); } } // if we are reqested with extension methods _results = new CMemberLookupResults(GetAllTypes(), _name); return !FError(); } public CMemberLookupResults GetResults() { return _results; } // Whether there were errors. public bool FError() { return !_swtFirst || _swtAmbig; } // The first symbol found. public Symbol SymFirst() { return _swtFirst.Sym; } public SymWithType SwtFirst() { return _swtFirst; } public SymWithType SwtInaccessible() { return _swtInaccess; } public EXPR GetObject() { return _obj; } public CType GetSourceType() { return _typeSrc; } public MemLookFlags GetFlags() { return _flags; } // Put all the types in a type array. public TypeArray GetAllTypes() { return GetSymbolLoader().getBSymmgr().AllocParams(_prgtype.Count, _prgtype.ToArray()); } /****************************************************************************** Reports errors. Only call this if FError() is true. ******************************************************************************/ public void ReportErrors() { Debug.Assert(FError()); // Report error. // NOTE: If the definition of FError changes, this code will need to change. Debug.Assert(!_swtFirst || _swtAmbig); if (_swtFirst) { // Ambiguous lookup. GetErrorContext().ErrorRef(ErrorCode.ERR_AmbigMember, _swtFirst, _swtAmbig); } else if (_swtInaccess) { if (!_swtInaccess.Sym.isUserCallable() && ((_flags & MemLookFlags.UserCallable) != 0)) GetErrorContext().Error(ErrorCode.ERR_CantCallSpecialMethod, _swtInaccess); else GetSemanticChecker().ReportAccessError(_swtInaccess, _symWhere, _typeQual); } else if ((_flags & MemLookFlags.Ctor) != 0) { if (_arity > 0) { GetErrorContext().Error(ErrorCode.ERR_BadCtorArgCount, _typeSrc.getAggregate(), _arity); } else { GetErrorContext().Error(ErrorCode.ERR_NoConstructors, _typeSrc.getAggregate()); } } else if ((_flags & MemLookFlags.Operator) != 0) { GetErrorContext().Error(ErrorCode.ERR_NoSuchMember, _typeSrc, _name); } else if ((_flags & MemLookFlags.Indexer) != 0) { GetErrorContext().Error(ErrorCode.ERR_BadIndexLHS, _typeSrc); } else if (_swtBad) { GetErrorContext().Error((_flags & MemLookFlags.MustBeInvocable) != 0 ? ErrorCode.ERR_NonInvocableMemberCalled : ErrorCode.ERR_CantCallSpecialMethod, _swtBad); } else if (_swtBogus) { ReportBogus(_swtBogus); } else if (_swtBadArity) { int cvar; switch (_swtBadArity.Sym.getKind()) { case SYMKIND.SK_MethodSymbol: Debug.Assert(_arity != 0); cvar = _swtBadArity.Sym.AsMethodSymbol().typeVars.size; GetErrorContext().ErrorRef(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym), cvar); break; case SYMKIND.SK_AggregateSymbol: cvar = _swtBadArity.Sym.AsAggregateSymbol().GetTypeVars().size; GetErrorContext().ErrorRef(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym), cvar); break; default: Debug.Assert(_arity != 0); ExpressionBinder.ReportTypeArgsNotAllowedError(GetSymbolLoader(), _arity, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym)); break; } } else { if ((_flags & MemLookFlags.ExtensionCall) != 0) { GetErrorContext().Error(ErrorCode.ERR_NoSuchMemberOrExtension, _typeSrc, _name); } else { GetErrorContext().Error(ErrorCode.ERR_NoSuchMember, _typeSrc, _name); } } } } }
using System; using Gtk; namespace Moscrif.IDE.Controls { public class MessageDialogUrl : Dialog { public MessageDialogUrl() { InicializeComponent(); } public MessageDialogUrl(DialogButtonType buttons, string primaryLabel, string secondaryLabel,string secondaryUrl, MessageType messageType,Gtk.Window parent) { InicializeComponent(); //if (parent == null) parent =MainClass.MainWindow; if (parent != null) TransientFor =parent; Buttons = buttons; PrimaryText = primaryLabel; linkBtn.Label = secondaryLabel; linkBtn.LinkUrl = secondaryUrl; MessageType = messageType; } public MessageDialogUrl(DialogButtonType buttons, string primaryLabel, string secondaryLabel,string secondaryUrl, MessageType messageType) { InicializeComponent(); TransientFor = MainClass.MainWindow; Buttons = buttons; PrimaryText = primaryLabel; linkBtn.Label = secondaryLabel; linkBtn.LinkUrl = secondaryUrl; MessageType = messageType; } public MessageDialogUrl(string[] labelButtons, string primaryLabel, string secondaryLabel,string secondaryUrl, MessageType messageType) { InicializeComponent(); TransientFor = MainClass.MainWindow; Buttons = buttons; PrimaryText = primaryLabel; linkBtn.Label = secondaryLabel; linkBtn.LinkUrl = secondaryUrl; MessageType = messageType; Widget[] oldButtons = ActionArea.Children; foreach (Widget w in oldButtons) ActionArea.Remove(w); int i =1; foreach (string s in labelButtons){ AddButton(s,-i); i++; } } public int ShowDialog(){ int result = this.Run(); this.Destroy(); return result; } private void InicializeComponent() { Resizable = false; HasSeparator = false; BorderWidth = 12; //Modal = true; label = new Label(); label.LineWrap = true; label.Selectable = true; label.UseMarkup = true; label.SetAlignment(0.0f, 0.0f); linkBtn = new Moscrif.IDE.Components.LinkButton(); linkBtn.SetAlignment(0.5f, 0.5f); icon = new Image(Stock.DialogInfo, IconSize.Dialog); icon.SetAlignment(0.5f, 0.0f); StockItem item = Stock.Lookup(icon.Stock); Title = item.Label; HBox hbox = new HBox(false, 12); VBox vbox = new VBox(false, 12); vbox.PackStart(label, false, false, 0); vbox.PackStart(linkBtn, true, true, 0); hbox.PackStart(icon, false, false, 0); hbox.PackStart(vbox, true, true, 0); VBox.PackStart(hbox, false, false, 0); hbox.ShowAll(); Buttons = MessageDialogUrl.DialogButtonType.OkCancel; } Label label; Image icon; Moscrif.IDE.Components.LinkButton linkBtn; public MessageType MessageType { get { if (icon.Stock == Stock.DialogInfo) return MessageType.Info; else if (icon.Stock == Stock.DialogQuestion) return MessageType.Question; else if (icon.Stock == Stock.DialogWarning) return MessageType.Warning; else return MessageType.Error; } set { StockItem item = Stock.Lookup(icon.Stock); bool setTitle = (Title == "") || (Title == item.Label); if (value == MessageType.Info) icon.Stock = Stock.DialogInfo; else if (value == MessageType.Question) icon.Stock = Stock.DialogQuestion; else if (value == MessageType.Warning) icon.Stock = Stock.DialogWarning; else icon.Stock = Stock.DialogError; if (setTitle) { item = Stock.Lookup(icon.Stock); Title = item.Label; } } } public string primaryText; public string PrimaryText { get { return primaryText; } set { primaryText = value; label.Markup = "<b>" + value + "</b>"; } } public string SecondaryText { get { return linkBtn.Label; } set { linkBtn.Label = value; } } DialogButtonType buttons; public DialogButtonType Buttons { get { return buttons; } set { Widget[] oldButtons = ActionArea.Children; foreach (Widget w in oldButtons) ActionArea.Remove(w); buttons = value; switch (buttons) { case DialogButtonType.None: // nothing break; case DialogButtonType.Ok: AddButton(Stock.Ok, ResponseType.Ok); break; case DialogButtonType.Close: AddButton(Stock.Close, ResponseType.Close); break; case DialogButtonType.Cancel: AddButton(Stock.Cancel, ResponseType.Cancel); break; case DialogButtonType.YesNo: AddButton(Stock.No, ResponseType.No); AddButton(Stock.Yes, ResponseType.Yes); break; case DialogButtonType.OkCancel: AddButton(Stock.Cancel, ResponseType.Cancel); AddButton(Stock.Ok, ResponseType.Ok); break; case DialogButtonType.YesNoCancel: AddButton(Stock.Cancel, ResponseType.Cancel); AddButton(Stock.No, ResponseType.No); AddButton(Stock.Yes, ResponseType.Yes); break; } } } public enum DialogButtonType { None, Ok, Close, Cancel, YesNo, OkCancel, YesNoCancel } } }
//////////////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2014 Paul Louth // // 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 Xunit; using Monad.Parsec; using Monad.Parsec.Language; namespace Monad.UnitTests { public class TokTests { [Fact] public void LexemeTest() { var lex = from l in Tok.Lexeme<ParserChar>(Prim.Character('A')) select l; var res = lex.Parse("A"); Assert.True(!res.IsFaulted); res = lex.Parse("A "); Assert.True(!res.IsFaulted); } [Fact] public void SymbolTest() { var sym = from s in Tok.Symbol("***") select s; var res = sym.Parse("*** "); Assert.True(!res.IsFaulted); } [Fact] public void OneLineComment() { var p = from v in Tok.OneLineComment(new HaskellDef()) select v; var res = p.Parse("-- This whole line is a comment"); Assert.True(!res.IsFaulted); } [Fact] public void MultiLineComment() { var p = from v in Tok.MultiLineComment(new HaskellDef()) select v; var res = p.Parse( @"{- This whole {- line is a comment and so is -} this one with nested comments this too -} let x=1"); var left = res.Value.Head().Item2.AsString(); Assert.True(!res.IsFaulted && left == " let x=1"); } [Fact] public void WhiteSpaceTest() { var p = from v in Tok.WhiteSpace(new HaskellDef()) select v; var res = p.Parse( @" {- This whole {- line is a comment and so is -} this one with nested comments this too -} let x=1"); var left = res.Value.Head().Item2.AsString(); Assert.True(!res.IsFaulted && left == "let x=1"); } [Fact] public void CharLiteralTest() { var p = from v in Tok.Chars.CharLiteral() select v; var res = p.Parse("'a' abc"); var left = res.Value.Head().Item2.AsString(); Assert.True(!res.IsFaulted && left == "abc"); Assert.True(res.Value.Head().Item1.Value.Value == 'a'); res = p.Parse("'\\n' abc"); Assert.True(res.Value.Head().Item1.Value.Value == '\n'); } [Fact] public void StringLiteralTest() { var p = from v in Tok.Strings.StringLiteral() select v; var res = p.Parse("\"abc\" def"); var left = res.Value.Head().Item2.AsString(); Assert.True(!res.IsFaulted && left == "def"); Assert.True(res.Value.Head().Item1.Value.AsString() == "abc"); res = p.Parse("\"ab\\t\\nc\" def"); Assert.True(res.Value.Head().Item1.Value.AsString() == "ab\t\nc"); } [Fact] public void NumbersIntegerTest() { var p = from v in Tok.Numbers.Integer() select v; var res = p.Parse("1234 def"); var left = res.Value.Head().Item2.AsString(); Assert.True(!res.IsFaulted && left == "def"); Assert.True(res.Value.Head().Item1.Value == 1234); } [Fact] public void NumbersHexTest() { var p = from v in Tok.Numbers.Hexadecimal() select v; var res = p.Parse("xAB34"); var left = res.Value.Head().Item2.AsString(); Assert.True(!res.IsFaulted); Assert.True(res.Value.Head().Item1.Value == 0xAB34); } [Fact] public void NumbersOctalTest() { var p = from v in Tok.Numbers.Octal() select v; var res = p.Parse("o777"); var left = res.Value.Head().Item2.AsString(); Assert.True(!res.IsFaulted); Assert.True(res.Value.Head().Item1.Value == 511); } [Fact] public void TestParens() { var r = Tok.Bracketing.Parens(Tok.Chars.CharLiteral()).Parse("( 'a' )"); Assert.True(!r.IsFaulted); Assert.True(r.Value.Head().Item1.Value.Value == 'a'); } [Fact] public void TestBraces() { var r = Tok.Bracketing.Braces(Tok.Chars.CharLiteral()).Parse("{ 'a' }"); Assert.True(!r.IsFaulted); Assert.True(r.Value.Head().Item1.Value.Value == 'a'); } [Fact] public void TestBrackets() { var r = Tok.Bracketing.Brackets(Tok.Chars.CharLiteral()).Parse("[ 'a' ]"); Assert.True(!r.IsFaulted); Assert.True(r.Value.Head().Item1.Value.Value == 'a'); } [Fact] public void TestAngles() { var r = Tok.Bracketing.Angles(Tok.Chars.CharLiteral()).Parse("< 'a' >"); Assert.True(!r.IsFaulted); Assert.True(r.Value.Head().Item1.Value.Value == 'a'); } [Fact] public void TestIdentifier() { var r = Tok.Id.Identifier(new HaskellDef()).Parse("onetWothree123 "); Assert.True(!r.IsFaulted); Assert.True(r.Value.Head().Item1.Value.AsString() == "onetWothree123"); } [Fact] public void TestReserved() { var def = new HaskellDef(); var r = Tok.Id.Reserved(def.ReservedNames.Head(), def).Parse(def.ReservedNames.Head() + " "); Assert.True(!r.IsFaulted); Assert.True(r.Value.Head().Item1.Value.AsString() == def.ReservedNames.Head()); } [Fact] public void TestOperator() { var def = new HaskellDef(); var r = Tok.Ops.Operator(def).Parse("&&* "); Assert.True(!r.IsFaulted); Assert.True(r.Value.Head().Item1.Value.AsString() == "&&*"); } [Fact] public void TestReservedOperator() { var def = new HaskellDef(); var r = Tok.Ops.ReservedOp("=>",def).Parse("=> "); Assert.True(!r.IsFaulted); Assert.True(r.Value.Head().Item1.Value.AsString() == "=>"); } } }
// 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.Diagnostics; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Concurrent.Tests { public class ConcurrentDictionaryTests { [Fact] public static void TestBasicScenarios() { ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>(); Task[] tks = new Task[2]; tks[0] = Task.Run(() => { var ret = cd.TryAdd(1, 11); if (!ret) { ret = cd.TryUpdate(1, 11, 111); Assert.True(ret); } ret = cd.TryAdd(2, 22); if (!ret) { ret = cd.TryUpdate(2, 22, 222); Assert.True(ret); } }); tks[1] = Task.Run(() => { var ret = cd.TryAdd(2, 222); if (!ret) { ret = cd.TryUpdate(2, 222, 22); Assert.True(ret); } ret = cd.TryAdd(1, 111); if (!ret) { ret = cd.TryUpdate(1, 111, 11); Assert.True(ret); } }); Task.WaitAll(tks); } [Fact] public static void TestAdd1() { TestAdd1(1, 1, 1, 10000); TestAdd1(5, 1, 1, 10000); TestAdd1(1, 1, 2, 5000); TestAdd1(1, 1, 5, 2000); TestAdd1(4, 0, 4, 2000); TestAdd1(16, 31, 4, 2000); TestAdd1(64, 5, 5, 5000); TestAdd1(5, 5, 5, 2500); } private static void TestAdd1(int cLevel, int initSize, int threads, int addsPerThread) { ConcurrentDictionary<int, int> dictConcurrent = new ConcurrentDictionary<int, int>(cLevel, 1); IDictionary<int, int> dict = dictConcurrent; int count = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < addsPerThread; j++) { dict.Add(j + ii * addsPerThread, -(j + ii * addsPerThread)); } if (Interlocked.Decrement(ref count) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { Assert.Equal(pair.Key, -pair.Value); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); int itemCount = threads * addsPerThread; for (int i = 0; i < itemCount; i++) expectKeys.Add(i); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), String.Format("The set of keys in the dictionary is are not the same as the expected" + Environment.NewLine + "TestAdd1(cLevel={0}, initSize={1}, threads={2}, addsPerThread={3})", cLevel, initSize, threads, addsPerThread) ); } // Finally, let's verify that the count is reported correctly. int expectedCount = threads * addsPerThread; Assert.Equal(expectedCount, dict.Count); Assert.Equal(expectedCount, dictConcurrent.ToArray().Length); } [Fact] public static void TestUpdate1() { TestUpdate1(1, 1, 10000); TestUpdate1(5, 1, 10000); TestUpdate1(1, 2, 5000); TestUpdate1(1, 5, 2001); TestUpdate1(4, 4, 2001); TestUpdate1(15, 5, 2001); TestUpdate1(64, 5, 5000); TestUpdate1(5, 5, 25000); } private static void TestUpdate1(int cLevel, int threads, int updatesPerThread) { IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); for (int i = 1; i <= updatesPerThread; i++) dict[i] = i; int running = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 1; j <= updatesPerThread; j++) { dict[j] = (ii + 2) * j; } if (Interlocked.Decrement(ref running) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { var div = pair.Value / pair.Key; var rem = pair.Value % pair.Key; Assert.Equal(0, rem); Assert.True(div > 1 && div <= threads+1, String.Format("* Invalid value={3}! TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread, div)); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); for (int i = 1; i <= updatesPerThread; i++) expectKeys.Add(i); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), String.Format("The set of keys in the dictionary is are not the same as the expected." + Environment.NewLine + "TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread) ); } } [Fact] public static void TestRead1() { TestRead1(1, 1, 10000); TestRead1(5, 1, 10000); TestRead1(1, 2, 5000); TestRead1(1, 5, 2001); TestRead1(4, 4, 2001); TestRead1(15, 5, 2001); TestRead1(64, 5, 5000); TestRead1(5, 5, 25000); } private static void TestRead1(int cLevel, int threads, int readsPerThread) { IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); for (int i = 0; i < readsPerThread; i += 2) dict[i] = i; int count = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < readsPerThread; j++) { int val = 0; if (dict.TryGetValue(j, out val)) { if (j % 2 == 1 || j != val) { Console.WriteLine("* TestRead1(cLevel={0}, threads={1}, readsPerThread={2})", cLevel, threads, readsPerThread); Assert.False(true, " > FAILED. Invalid element in the dictionary."); } } else { if (j % 2 == 0) { Console.WriteLine("* TestRead1(cLevel={0}, threads={1}, readsPerThread={2})", cLevel, threads, readsPerThread); Assert.False(true, " > FAILED. Element missing from the dictionary"); } } } if (Interlocked.Decrement(ref count) == 0) mre.Set(); }); } mre.WaitOne(); } } [Fact] public static void TestRemove1() { TestRemove1(1, 1, 10000); TestRemove1(5, 1, 1000); TestRemove1(1, 5, 2001); TestRemove1(4, 4, 2001); TestRemove1(15, 5, 2001); TestRemove1(64, 5, 5000); } private static void TestRemove1(int cLevel, int threads, int removesPerThread) { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); string methodparameters = string.Format("* TestRemove1(cLevel={0}, threads={1}, removesPerThread={2})", cLevel, threads, removesPerThread); int N = 2 * threads * removesPerThread; for (int i = 0; i < N; i++) dict[i] = -i; // The dictionary contains keys [0..N), each key mapped to a value equal to the key. // Threads will cooperatively remove all even keys int running = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < removesPerThread; j++) { int value; int key = 2 * (ii + j * threads); Assert.True(dict.TryRemove(key, out value), "Failed to remove an element! " + methodparameters); Assert.Equal(-key, value); } if (Interlocked.Decrement(ref running) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { Assert.Equal(pair.Key, -pair.Value); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); for (int i = 0; i < (threads * removesPerThread); i++) expectKeys.Add(2 * i + 1); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), " > Unexpected key value! " + methodparameters); } // Finally, let's verify that the count is reported correctly. Assert.Equal(expectKeys.Count, dict.Count); Assert.Equal(expectKeys.Count, dict.ToArray().Length); } [Fact] public static void TestRemove2() { TestRemove2(1); TestRemove2(10); TestRemove2(5000); } private static void TestRemove2(int removesPerThread) { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(); for (int i = 0; i < removesPerThread; i++) dict[i] = -i; // The dictionary contains keys [0..N), each key mapped to a value equal to the key. // Threads will cooperatively remove all even keys. const int SIZE = 2; int running = SIZE; bool[][] seen = new bool[SIZE][]; for (int i = 0; i < SIZE; i++) seen[i] = new bool[removesPerThread]; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int t = 0; t < SIZE; t++) { int thread = t; Task.Run( () => { for (int key = 0; key < removesPerThread; key++) { int value; if (dict.TryRemove(key, out value)) { seen[thread][key] = true; Assert.Equal(-key, value); } } if (Interlocked.Decrement(ref running) == 0) mre.Set(); }); } mre.WaitOne(); } Assert.Equal(0, dict.Count); for (int i = 0; i < removesPerThread; i++) { Assert.False(seen[0][i] == seen[1][i], String.Format("> FAILED. Two threads appear to have removed the same element. TestRemove2(removesPerThread={0})", removesPerThread) ); } } [Fact] public static void TestRemove3() { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(); dict[99] = -99; ICollection<KeyValuePair<int, int>> col = dict; // Make sure we cannot "remove" a key/value pair which is not in the dictionary for (int i = 0; i < 200; i++) { if (i != 99) { Assert.False(col.Remove(new KeyValuePair<int, int>(i, -99)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(i, -99)"); Assert.False(col.Remove(new KeyValuePair<int, int>(99, -i)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(99, -i)"); } } // Can we remove a key/value pair successfully? Assert.True(col.Remove(new KeyValuePair<int, int>(99, -99)), "Failed to remove existing key/value pair"); // Make sure the key/value pair is gone Assert.False(col.Remove(new KeyValuePair<int, int>(99, -99)), "Should not remove the key/value pair which has been removed"); // And that the dictionary is empty. We will check the count in a few different ways: Assert.Equal(0, dict.Count); Assert.Equal(0, dict.ToArray().Length); } [Fact] public static void TestGetOrAdd() { TestGetOrAddOrUpdate(1, 1, 1, 10000, true); TestGetOrAddOrUpdate(5, 1, 1, 10000, true); TestGetOrAddOrUpdate(1, 1, 2, 5000, true); TestGetOrAddOrUpdate(1, 1, 5, 2000, true); TestGetOrAddOrUpdate(4, 0, 4, 2000, true); TestGetOrAddOrUpdate(16, 31, 4, 2000, true); TestGetOrAddOrUpdate(64, 5, 5, 5000, true); TestGetOrAddOrUpdate(5, 5, 5, 25000, true); } [Fact] public static void TestAddOrUpdate() { TestGetOrAddOrUpdate(1, 1, 1, 10000, false); TestGetOrAddOrUpdate(5, 1, 1, 10000, false); TestGetOrAddOrUpdate(1, 1, 2, 5000, false); TestGetOrAddOrUpdate(1, 1, 5, 2000, false); TestGetOrAddOrUpdate(4, 0, 4, 2000, false); TestGetOrAddOrUpdate(16, 31, 4, 2000, false); TestGetOrAddOrUpdate(64, 5, 5, 5000, false); TestGetOrAddOrUpdate(5, 5, 5, 25000, false); } private static void TestGetOrAddOrUpdate(int cLevel, int initSize, int threads, int addsPerThread, bool isAdd) { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); int count = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < addsPerThread; j++) { if (isAdd) { //call one of the overloads of GetOrAdd switch (j % 3) { case 0: dict.GetOrAdd(j, -j); break; case 1: dict.GetOrAdd(j, x => -x); break; case 2: dict.GetOrAdd(j, (x,m) => x * m, -1); break; } } else { switch (j % 3) { case 0: dict.AddOrUpdate(j, -j, (k, v) => -j); break; case 1: dict.AddOrUpdate(j, (k) => -k, (k, v) => -k); break; case 2: dict.AddOrUpdate(j, (k,m) => k*m, (k, v, m) => k * m, -1); break; } } } if (Interlocked.Decrement(ref count) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { Assert.Equal(pair.Key, -pair.Value); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); for (int i = 0; i < addsPerThread; i++) expectKeys.Add(i); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), String.Format("* Test '{4}': Level={0}, initSize={1}, threads={2}, addsPerThread={3})" + Environment.NewLine + "> FAILED. The set of keys in the dictionary is are not the same as the expected.", cLevel, initSize, threads, addsPerThread, isAdd ? "GetOrAdd" : "GetOrUpdate")); } // Finally, let's verify that the count is reported correctly. Assert.Equal(addsPerThread, dict.Count); Assert.Equal(addsPerThread, dict.ToArray().Length); } [Fact] public static void TestBugFix669376() { var cd = new ConcurrentDictionary<string, int>(new OrdinalStringComparer()); cd["test"] = 10; Assert.True(cd.ContainsKey("TEST"), "Customized comparer didn't work"); } private class OrdinalStringComparer : IEqualityComparer<string> { public bool Equals(string x, string y) { var xlower = x.ToLowerInvariant(); var ylower = y.ToLowerInvariant(); return string.CompareOrdinal(xlower, ylower) == 0; } public int GetHashCode(string obj) { return 0; } } [Fact] public static void TestConstructor() { var dictionary = new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) }); Assert.False(dictionary.IsEmpty); Assert.Equal(1, dictionary.Keys.Count); Assert.Equal(1, dictionary.Values.Count); } [Fact] public static void TestDebuggerAttributes() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new ConcurrentDictionary<string, int>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new ConcurrentDictionary<string, int>()); } [Fact] public static void TestConstructor_Negative() { Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>((IEqualityComparer<int>)null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null IEqualityComparer is passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null, EqualityComparer<int>.Default)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null collection and non null IEqualityComparer passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) }, null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when non null collection and null IEqualityComparer passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<string, int>(new[] { new KeyValuePair<string, int>(null, 1) })); // "TestConstructor: FAILED. Constructor didn't throw ANE when collection has null key passed"); Assert.Throws<ArgumentException>( () => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1), new KeyValuePair<int, int>(1, 2) })); // "TestConstructor: FAILED. Constructor didn't throw AE when collection has duplicate keys passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>(1, null, EqualityComparer<int>.Default)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>(1, new[] { new KeyValuePair<int, int>(1, 1) }, null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>(1, 1, null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed"); Assert.Throws<ArgumentOutOfRangeException>( () => new ConcurrentDictionary<int, int>(0, 10)); // "TestConstructor: FAILED. Constructor didn't throw AORE when <1 concurrencyLevel passed"); Assert.Throws<ArgumentOutOfRangeException>( () => new ConcurrentDictionary<int, int>(-1, 0)); // "TestConstructor: FAILED. Constructor didn't throw AORE when < 0 capacity passed"); } [Fact] public static void TestExceptions() { var dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>( () => dictionary.TryAdd(null, 0)); // "TestExceptions: FAILED. TryAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.ContainsKey(null)); // "TestExceptions: FAILED. Contains didn't throw ANE when null key is passed"); int item; Assert.Throws<ArgumentNullException>( () => dictionary.TryRemove(null, out item)); // "TestExceptions: FAILED. TryRemove didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.TryGetValue(null, out item)); // "TestExceptions: FAILED. TryGetValue didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => { var x = dictionary[null]; }); // "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed"); Assert.Throws<KeyNotFoundException>( () => { var x = dictionary["1"]; }); // "TestExceptions: FAILED. this[] TryGetValue didn't throw KeyNotFoundException!"); Assert.Throws<ArgumentNullException>( () => dictionary[null] = 1); // "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd(null, (k,m) => 0, 0)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd("1", null, 0)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null valueFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd(null, (k) => 0)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd("1", null)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null valueFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd(null, 0)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate(null, (k, m) => 0, (k, v, m) => 0, 42)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate("1", (k, m) => 0, null, 42)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null updateFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate("1", null, (k, v, m) => 0, 42)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null addFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate(null, (k) => 0, (k, v) => 0)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate("1", null, (k, v) => 0)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null updateFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate(null, (k) => 0, null)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null addFactory is passed"); dictionary.TryAdd("1", 1); Assert.Throws<ArgumentException>( () => ((IDictionary<string, int>)dictionary).Add("1", 2)); // "TestExceptions: FAILED. IDictionary didn't throw AE when duplicate key is passed"); } [Fact] public static void TestIDictionary() { IDictionary dictionary = new ConcurrentDictionary<string, int>(); Assert.False(dictionary.IsReadOnly); foreach (var entry in dictionary) { Assert.False(true, "TestIDictionary: FAILED. GetEnumerator retuned items when the dictionary is empty"); } const int SIZE = 10; for (int i = 0; i < SIZE; i++) dictionary.Add(i.ToString(), i); Assert.Equal(SIZE, dictionary.Count); //test contains Assert.False(dictionary.Contains(1), "TestIDictionary: FAILED. Contain retuned true for incorrect key type"); Assert.False(dictionary.Contains("100"), "TestIDictionary: FAILED. Contain retuned true for incorrect key"); Assert.True(dictionary.Contains("1"), "TestIDictionary: FAILED. Contain retuned false for correct key"); //test GetEnumerator int count = 0; foreach (var obj in dictionary) { DictionaryEntry entry = (DictionaryEntry)obj; string key = (string)entry.Key; int value = (int)entry.Value; int expectedValue = int.Parse(key); Assert.True(value == expectedValue, String.Format("TestIDictionary: FAILED. Unexpected value returned from GetEnumerator, expected {0}, actual {1}", value, expectedValue)); count++; } Assert.Equal(SIZE, count); Assert.Equal(SIZE, dictionary.Keys.Count); Assert.Equal(SIZE, dictionary.Values.Count); //Test Remove dictionary.Remove("9"); Assert.Equal(SIZE - 1, dictionary.Count); //Test this[] for (int i = 0; i < dictionary.Count; i++) Assert.Equal(i, (int)dictionary[i.ToString()]); dictionary["1"] = 100; // try a valid setter Assert.Equal(100, (int)dictionary["1"]); //nonsexist key Assert.Null(dictionary["NotAKey"]); } [Fact] public static void TestIDictionary_Negative() { IDictionary dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>( () => dictionary.Add(null, 1)); // "TestIDictionary: FAILED. Add didn't throw ANE when null key is passed"); Assert.Throws<ArgumentException>( () => dictionary.Add(1, 1)); // "TestIDictionary: FAILED. Add didn't throw AE when incorrect key type is passed"); Assert.Throws<ArgumentException>( () => dictionary.Add("1", "1")); // "TestIDictionary: FAILED. Add didn't throw AE when incorrect value type is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.Contains(null)); // "TestIDictionary: FAILED. Contain didn't throw ANE when null key is passed"); //Test Remove Assert.Throws<ArgumentNullException>( () => dictionary.Remove(null)); // "TestIDictionary: FAILED. Remove didn't throw ANE when null key is passed"); //Test this[] Assert.Throws<ArgumentNullException>( () => { object val = dictionary[null]; }); // "TestIDictionary: FAILED. this[] getter didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary[null] = 0); // "TestIDictionary: FAILED. this[] setter didn't throw ANE when null key is passed"); Assert.Throws<ArgumentException>( () => dictionary[1] = 0); // "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid key type is passed"); Assert.Throws<ArgumentException>( () => dictionary["1"] = "0"); // "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid value type is passed"); } [Fact] public static void TestICollection() { ICollection dictionary = new ConcurrentDictionary<int, int>(); Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!"); int key = -1; int value = +1; //add one item to the dictionary ((ConcurrentDictionary<int, int>)dictionary).TryAdd(key, value); var objectArray = new Object[1]; dictionary.CopyTo(objectArray, 0); Assert.Equal(key, ((KeyValuePair<int, int>)objectArray[0]).Key); Assert.Equal(value, ((KeyValuePair<int, int>)objectArray[0]).Value); var keyValueArray = new KeyValuePair<int, int>[1]; dictionary.CopyTo(keyValueArray, 0); Assert.Equal(key, keyValueArray[0].Key); Assert.Equal(value, keyValueArray[0].Value); var entryArray = new DictionaryEntry[1]; dictionary.CopyTo(entryArray, 0); Assert.Equal(key, (int)entryArray[0].Key); Assert.Equal(value, (int)entryArray[0].Value); } [Fact] public static void TestICollection_Negative() { ICollection dictionary = new ConcurrentDictionary<int, int>(); Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!"); Assert.Throws<NotSupportedException>(() => { var obj = dictionary.SyncRoot; }); // "TestICollection: FAILED. SyncRoot property didn't throw"); Assert.Throws<ArgumentNullException>(() => dictionary.CopyTo(null, 0)); // "TestICollection: FAILED. CopyTo didn't throw ANE when null Array is passed"); Assert.Throws<ArgumentOutOfRangeException>(() => dictionary.CopyTo(new object[] { }, -1)); // "TestICollection: FAILED. CopyTo didn't throw AORE when negative index passed"); //add one item to the dictionary ((ConcurrentDictionary<int, int>)dictionary).TryAdd(1, 1); Assert.Throws<ArgumentException>(() => dictionary.CopyTo(new object[] { }, 0)); // "TestICollection: FAILED. CopyTo didn't throw AE when the Array size is smaller than the dictionary count"); } [Fact] public static void TestClear() { var dictionary = new ConcurrentDictionary<int, int>(); for (int i = 0; i < 10; i++) dictionary.TryAdd(i, i); Assert.Equal(10, dictionary.Count); dictionary.Clear(); Assert.Equal(0, dictionary.Count); int item; Assert.False(dictionary.TryRemove(1, out item), "TestClear: FAILED. TryRemove succeeded after Clear"); Assert.True(dictionary.IsEmpty, "TestClear: FAILED. IsEmpty returned false after Clear"); } public static void TestTryUpdate() { var dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>( () => dictionary.TryUpdate(null, 0, 0)); // "TestTryUpdate: FAILED. TryUpdate didn't throw ANE when null key is passed"); for (int i = 0; i < 10; i++) dictionary.TryAdd(i.ToString(), i); for (int i = 0; i < 10; i++) { Assert.True(dictionary.TryUpdate(i.ToString(), i + 1, i), "TestTryUpdate: FAILED. TryUpdate failed!"); Assert.Equal(i + 1, dictionary[i.ToString()]); } //test TryUpdate concurrently dictionary.Clear(); for (int i = 0; i < 1000; i++) dictionary.TryAdd(i.ToString(), i); var mres = new ManualResetEventSlim(); Task[] tasks = new Task[10]; ThreadLocal<ThreadData> updatedKeys = new ThreadLocal<ThreadData>(true); for (int i = 0; i < tasks.Length; i++) { // We are creating the Task using TaskCreationOptions.LongRunning because... // there is no guarantee that the Task will be created on another thread. // There is also no guarantee that using this TaskCreationOption will force // it to be run on another thread. tasks[i] = Task.Factory.StartNew((obj) => { mres.Wait(); int index = (((int)obj) + 1) + 1000; updatedKeys.Value = new ThreadData(); updatedKeys.Value.ThreadIndex = index; for (int j = 0; j < dictionary.Count; j++) { if (dictionary.TryUpdate(j.ToString(), index, j)) { if (dictionary[j.ToString()] != index) { updatedKeys.Value.Succeeded = false; return; } updatedKeys.Value.Keys.Add(j.ToString()); } } }, i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } mres.Set(); Task.WaitAll(tasks); int numberSucceeded = 0; int totalKeysUpdated = 0; foreach (var threadData in updatedKeys.Values) { totalKeysUpdated += threadData.Keys.Count; if (threadData.Succeeded) numberSucceeded++; } Assert.True(numberSucceeded == tasks.Length, "One or more threads failed!"); Assert.True(totalKeysUpdated == dictionary.Count, String.Format("TestTryUpdate: FAILED. The updated keys count doesn't match the dictionary count, expected {0}, actual {1}", dictionary.Count, totalKeysUpdated)); foreach (var value in updatedKeys.Values) { for (int i = 0; i < value.Keys.Count; i++) Assert.True(dictionary[value.Keys[i]] == value.ThreadIndex, String.Format("TestTryUpdate: FAILED. The updated value doesn't match the thread index, expected {0} actual {1}", value.ThreadIndex, dictionary[value.Keys[i]])); } //test TryUpdate with non atomic values (intPtr > 8) var dict = new ConcurrentDictionary<int, Struct16>(); dict.TryAdd(1, new Struct16(1, -1)); Assert.True(dict.TryUpdate(1, new Struct16(2, -2), new Struct16(1, -1)), "TestTryUpdate: FAILED. TryUpdate failed for non atomic values ( > 8 bytes)"); } #region Helper Classes and Methods private class ThreadData { public int ThreadIndex; public bool Succeeded = true; public List<string> Keys = new List<string>(); } private struct Struct16 : IEqualityComparer<Struct16> { public long L1, L2; public Struct16(long l1, long l2) { L1 = l1; L2 = l2; } public bool Equals(Struct16 x, Struct16 y) { return x.L1 == y.L1 && x.L2 == y.L2; } public int GetHashCode(Struct16 obj) { return (int)L1; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using TestLibrary; using System.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Reflection.Emit.ILGeneration.Tests { public class ILGeneratorEmit1 { [Fact] public void PosTest1() { string name = "Assembly1"; AssemblyName asmname = new AssemblyName(name); AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run); ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1"); TypeBuilder tb = modbuild.DefineType("C1", TypeAttributes.Public); MethodBuilder mbuild = tb.DefineMethod("meth1", MethodAttributes.Public, typeof(int), new Type[] { }); int expectedRet = 1; // generate code for the method that we are going to use as MethodInfo in ILGenerator.Emit() ILGenerator ilgen = mbuild.GetILGenerator(); ilgen.Emit(OpCodes.Ldc_I4, expectedRet); ilgen.Emit(OpCodes.Ret); // create the type where this method is in Type tp = tb.CreateTypeInfo().AsType(); MethodInfo mi = tp.GetMethod("meth1"); TypeBuilder tb2 = modbuild.DefineType("C2", TypeAttributes.Public); MethodBuilder mbuild2 = tb2.DefineMethod("meth2", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { }); // generate code for the method which will be invoking the first method ILGenerator ilgen2 = mbuild2.GetILGenerator(); ilgen2.Emit(OpCodes.Newobj, tp.GetConstructor(new Type[] { })); ilgen2.Emit(OpCodes.Call, mi); ilgen2.Emit(OpCodes.Ret); // create the type whose method will be invoking the MethodInfo method Type tp2 = tb2.CreateTypeInfo().AsType(); MethodInfo md = tp2.GetMethod("meth2"); // meth2 should invoke meth1 which should return value from meth1 int ret = (int)md.Invoke(null, null); Assert.Equal(ret, expectedRet); } [Fact] public void PosTest2() { string name = "Assembly1"; AssemblyName asmname = new AssemblyName(name); AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run); ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1"); TypeBuilder tb = modbuild.DefineType("C1", TypeAttributes.Public); MethodBuilder mbuild = tb.DefineMethod("meth1", MethodAttributes.Public, typeof(int), new Type[] { }); int expectedRet = 12; // generate code for the method that we are going to use as MethodInfo in ILGenerator.Emit() ILGenerator ilgen = mbuild.GetILGenerator(); ilgen.Emit(OpCodes.Ldc_I4, expectedRet); ilgen.Emit(OpCodes.Ret); // create the type where this method is in Type tp = tb.CreateTypeInfo().AsType(); MethodInfo mi = tp.GetMethod("meth1"); TypeBuilder tb2 = modbuild.DefineType("C2", TypeAttributes.Public); MethodBuilder mbuild2 = tb2.DefineMethod("meth2", MethodAttributes.Public, typeof(int), new Type[] { }); // generate code for the method which will be invoking the first method ILGenerator ilgen2 = mbuild2.GetILGenerator(); ilgen2.Emit(OpCodes.Newobj, tp.GetConstructor(new Type[] { })); ilgen2.Emit(OpCodes.Callvirt, mi); ilgen2.Emit(OpCodes.Ret); // create the type whose method will be invoking the MethodInfo method Type tp2 = tb2.CreateTypeInfo().AsType(); MethodInfo md = tp2.GetMethod("meth2"); // meth2 should invoke meth1 which should return value 'methodRet' int ret = (int)md.Invoke(Activator.CreateInstance(tp2), null); Assert.Equal(ret, expectedRet); } [Fact] public void PosTest3() { string name = "Assembly1"; AssemblyName asmname = new AssemblyName(name); AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run); ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1"); TypeBuilder tb = modbuild.DefineType("C1", TypeAttributes.Public); MethodBuilder mbuild = tb.DefineMethod("meth1", MethodAttributes.Public, typeof(int), new Type[] { }); mbuild.DefineGenericParameters(new string[] { "T" }); int expectedRet = 101; // generate code for the method that we are going to use as MethodInfo in ILGenerator.Emit() ILGenerator ilgen = mbuild.GetILGenerator(); ilgen.Emit(OpCodes.Ldc_I4, expectedRet); ilgen.Emit(OpCodes.Ret); // create the type where this method is in Type tp = tb.CreateTypeInfo().AsType(); MethodInfo mi = tp.GetMethod("meth1"); MethodInfo miConstructed = mi.MakeGenericMethod(typeof(int)); TypeBuilder tb2 = modbuild.DefineType("C2", TypeAttributes.Public); MethodBuilder mbuild2 = tb2.DefineMethod("meth2", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { }); // generate code for the method which will be invoking the first method ILGenerator ilgen2 = mbuild2.GetILGenerator(); ilgen2.Emit(OpCodes.Newobj, tp.GetConstructor(new Type[] { })); ilgen2.Emit(OpCodes.Callvirt, miConstructed); ilgen2.Emit(OpCodes.Ret); // create the type whose method will be invoking the MethodInfo method Type tp2 = tb2.CreateTypeInfo().AsType(); MethodInfo md = tp2.GetMethod("meth2"); // meth2 should invoke meth1 which should return value 'methodRet' int ret = (int)md.Invoke(null, null); Assert.Equal(ret, expectedRet); } [Fact] public void PosTest4() { string name = "Assembly1"; AssemblyName asmname = new AssemblyName(name); // create a dynamic assembly & module AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run); ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1"); TypeBuilder tb = modbuild.DefineType("C1", TypeAttributes.Public); tb.DefineGenericParameters(new string[] { "T" }); MethodBuilder mbuild = tb.DefineMethod("meth1", MethodAttributes.Public, typeof(long), new Type[] { }); long expectedRet = 500000; // generate code for the method that we are going to use as MethodInfo in ILGenerator.Emit() ILGenerator ilgen = mbuild.GetILGenerator(); ilgen.Emit(OpCodes.Ldc_I8, expectedRet); ilgen.Emit(OpCodes.Ret); // create the type where this method is in Type tp = tb.CreateTypeInfo().AsType(); Type tpConstructed = tp.MakeGenericType(typeof(int)); MethodInfo mi = tpConstructed.GetMethod("meth1"); TypeBuilder tb2 = modbuild.DefineType("C2", TypeAttributes.Public); MethodBuilder mbuild2 = tb2.DefineMethod("meth2", MethodAttributes.Public | MethodAttributes.Static, typeof(long), new Type[] { }); // generate code for the method which will be invoking the first method ILGenerator ilgen2 = mbuild2.GetILGenerator(); ilgen2.Emit(OpCodes.Newobj, tpConstructed.GetConstructor(new Type[] { })); ilgen2.Emit(OpCodes.Callvirt, mi); ilgen2.Emit(OpCodes.Ret); // create the type whose method will be invoking the MethodInfo method Type tp2 = tb2.CreateTypeInfo().AsType(); MethodInfo md = tp2.GetMethod("meth2"); // meth2 should invoke meth1 which should return value 'methodRet' long ret = (long)md.Invoke(null, null); Assert.Equal(ret, expectedRet); } [Fact] public void PosTest5() { string name = "Assembly1"; AssemblyName asmname = new AssemblyName(name); // create a dynamic assembly & module AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run); ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1"); TypeBuilder tb = modbuild.DefineType("C1", TypeAttributes.Public); tb.DefineGenericParameters(new string[] { "T" }); MethodBuilder mbuild = tb.DefineMethod("meth1", MethodAttributes.Public, typeof(int), new Type[] { }); mbuild.DefineGenericParameters(new string[] { "U" }); int expectedRet = 1; // generate code for the method that we are going to use as MethodInfo in ILGenerator.Emit() ILGenerator ilgen = mbuild.GetILGenerator(); ilgen.Emit(OpCodes.Ldc_I4, expectedRet); ilgen.Emit(OpCodes.Ret); // create the type where this method is in Type tp = tb.CreateTypeInfo().AsType(); Type tpConstructed = tp.MakeGenericType(typeof(int)); MethodInfo mi = tpConstructed.GetMethod("meth1"); MethodInfo miConstructed = mi.MakeGenericMethod(typeof(string)); TypeBuilder tb2 = modbuild.DefineType("C2", TypeAttributes.Public); MethodBuilder mbuild2 = tb2.DefineMethod("meth2", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { }); // generate code for the method which will be invoking the first method ILGenerator ilgen2 = mbuild2.GetILGenerator(); ilgen2.Emit(OpCodes.Newobj, tpConstructed.GetConstructor(new Type[] { })); ilgen2.Emit(OpCodes.Callvirt, miConstructed); ilgen2.Emit(OpCodes.Ret); // create the type whose method will be invoking the MethodInfo method Type tp2 = tb2.CreateTypeInfo().AsType(); MethodInfo md = tp2.GetMethod("meth2"); // meth2 should invoke meth1 which should return value 'methodRet' int ret = (int)md.Invoke(null, null); Assert.Equal(ret, expectedRet); } [Fact] public void NegTest() { string name = "Assembly1"; AssemblyName asmname = new AssemblyName(); asmname.Name = name; AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run); ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1"); MethodBuilder methbuild = modbuild.DefineGlobalMethod("method1", MethodAttributes.Public | MethodAttributes.Static, typeof(Type), new Type[] { }); ILGenerator ilgen = methbuild.GetILGenerator(); MethodInfo mi = null; Assert.Throws<ArgumentNullException>(() => { ilgen.Emit(OpCodes.Call, mi); }); } } }
using System; using System.Diagnostics; using MatterHackers.Agg.Font; using MatterHackers.Agg.Image; using MatterHackers.Agg.RasterizerScanline; using MatterHackers.Agg.Transform; using MatterHackers.Agg.UI; using MatterHackers.Agg.UI.Examples; using MatterHackers.Agg.VertexSource; using MatterHackers.VectorMath; namespace MatterHackers.Agg { public class blur : GuiWidget, IDemoApp { private RadioButtonGroup m_method; private Slider m_radius; private PolygonEditWidget m_shadow_ctrl; private CheckBox m_channel_r; private CheckBox m_channel_g; private CheckBox m_channel_b; private CheckBox m_FlattenCurves; private IVertexSource m_path; private FlattenCurves m_shape; private ScanlineRasterizer m_ras = new ScanlineRasterizer(); private ScanlineCachePacked8 m_sl; private ImageBuffer m_rbuf2; //agg::stack_blur <agg::rgba8, agg::stack_blur_calc_rgb<> > m_stack_blur; private RecursiveBlur m_recursive_blur = new RecursiveBlur(new recursive_blur_calc_rgb()); private RectangleDouble m_shape_bounds; private Stopwatch stopwatch = new Stopwatch(); public blur() { m_rbuf2 = new ImageBuffer(); m_shape_bounds = new RectangleDouble(); m_method = new RadioButtonGroup(new Vector2(10.0, 10.0), new Vector2(130.0, 60.0)); m_radius = new Slider(new Vector2(130 + 10.0, 10.0 + 4.0), new Vector2(290, 8.0)); m_shadow_ctrl = new PolygonEditWidget(4); m_channel_r = new CheckBox(10.0, 80.0, "Red"); m_channel_g = new CheckBox(10.0, 95.0, "Green"); m_channel_b = new CheckBox(10.0, 110.0, "Blue"); m_FlattenCurves = new CheckBox(10, 315, "Convert And Flatten Curves"); m_FlattenCurves.Checked = true; AddChild(m_method); m_method.AddRadioButton("Stack Blur"); m_method.AddRadioButton("Recursive Blur"); m_method.AddRadioButton("Channels"); m_method.SelectedIndex = 1; AddChild(m_radius); m_radius.SetRange(0.0, 40.0); m_radius.Value = 15.0; m_radius.Text = "Blur Radius={0:F2}"; AddChild(m_shadow_ctrl); AddChild(m_channel_r); AddChild(m_channel_g); AddChild(m_channel_b); AddChild(m_FlattenCurves); m_channel_g.Checked = true; m_sl = new ScanlineCachePacked8(); StyledTypeFace typeFaceForLargeA = new StyledTypeFace(LiberationSansFont.Instance, 300, flattenCurves: false); m_path = typeFaceForLargeA.GetGlyphForCharacter('a'); Affine shape_mtx = Affine.NewIdentity(); shape_mtx *= Affine.NewTranslation(150, 100); m_path = new VertexSourceApplyTransform(m_path, shape_mtx); m_shape = new FlattenCurves(m_path); bounding_rect.bounding_rect_single(m_shape, 0, ref m_shape_bounds); m_shadow_ctrl.SetXN(0, m_shape_bounds.Left); m_shadow_ctrl.SetYN(0, m_shape_bounds.Bottom); m_shadow_ctrl.SetXN(1, m_shape_bounds.Right); m_shadow_ctrl.SetYN(1, m_shape_bounds.Bottom); m_shadow_ctrl.SetXN(2, m_shape_bounds.Right); m_shadow_ctrl.SetYN(2, m_shape_bounds.Top); m_shadow_ctrl.SetXN(3, m_shape_bounds.Left); m_shadow_ctrl.SetYN(3, m_shape_bounds.Top); m_shadow_ctrl.line_color(new ColorF(0, 0.3, 0.5, 0.3)); } public string Title { get; } = "Gaussian and Stack Blur"; public string DemoCategory { get; } = "Bitmap"; public string DemoDescription { get; } = @"Now you can blur rendered images rather fast! There two algorithms are used: Stack Blur by Mario Klingemann and Fast Recursive Gaussian Filter, described here and here (PDF). The speed of both methods does not depend on the filter radius. Mario's method works 3-5 times faster; it doesn't produce exactly Gaussian response, but pretty fair for most practical purposes. The recursive filter uses floating point arithmetic and works slower. But it is true Gaussian filter, with theoretically infinite impulse response. The radius (actually 2*sigma value) can be fractional and the filter produces quite adequate result."; public override void OnParentChanged(EventArgs e) { AnchorAll(); base.OnParentChanged(e); } public override void OnMouseMove(MouseEventArgs mouseEvent) { base.OnMouseMove(mouseEvent); Invalidate(); } public override void OnDraw(Graphics2D graphics2D) { ImageBuffer widgetsSubImage = ImageBuffer.NewSubImageReference(graphics2D.DestImage, graphics2D.GetClippingRect()); ImageClippingProxy clippingProxy = new ImageClippingProxy(widgetsSubImage); clippingProxy.clear(new ColorF(1, 1, 1)); m_ras.SetVectorClipBox(0, 0, Width, Height); Affine move = Affine.NewTranslation(10, 10); Perspective shadow_persp = new Perspective(m_shape_bounds.Left, m_shape_bounds.Bottom, m_shape_bounds.Right, m_shape_bounds.Top, m_shadow_ctrl.polygon()); IVertexSource shadow_trans; if (m_FlattenCurves.Checked) { shadow_trans = new VertexSourceApplyTransform(m_shape, shadow_persp); } else { shadow_trans = new VertexSourceApplyTransform(m_path, shadow_persp); // this will make it very smooth after the transform //shadow_trans = new conv_curve(shadow_trans); } // Render shadow m_ras.add_path(shadow_trans); ScanlineRenderer scanlineRenderer = new ScanlineRenderer(); scanlineRenderer.RenderSolid(clippingProxy, m_ras, m_sl, new ColorF(0.2, 0.3, 0).ToColor()); // Calculate the bounding box and extend it by the blur radius RectangleDouble bbox = new RectangleDouble(); bounding_rect.bounding_rect_single(shadow_trans, 0, ref bbox); bbox.Left -= m_radius.Value; bbox.Bottom -= m_radius.Value; bbox.Right += m_radius.Value; bbox.Top += m_radius.Value; if (m_method.SelectedIndex == 1) { // The recursive blur method represents the true Gaussian Blur, // with theoretically infinite kernel. The restricted window size // results in extra influence of edge pixels. It's impossible to // solve correctly, but extending the right and top areas to another // radius value produces fair result. //------------------ bbox.Right += m_radius.Value; bbox.Top += m_radius.Value; } stopwatch.Restart(); if (m_method.SelectedIndex != 2) { // Create a new pixel renderer and attach it to the main one as a child image. // It returns true if the attachment succeeded. It fails if the rectangle // (bbox) is fully clipped. //------------------ #if SourceDepth24 ImageBuffer image2 = new ImageBuffer(new BlenderBGR()); #else ImageBuffer image2 = new ImageBuffer(new BlenderBGRA()); #endif if (image2.Attach(widgetsSubImage, (int)bbox.Left, (int)bbox.Bottom, (int)bbox.Right, (int)bbox.Top)) { // Blur it if (m_method.SelectedIndex == 0) { // More general method, but 30-40% slower. //------------------ //m_stack_blur.blur(pixf2, agg::uround(m_radius.Value)); // Faster, but bore specific. // Works only for 8 bits per channel and only with radii <= 254. //------------------ stack_blur test = new stack_blur(); test.Blur(image2, agg_basics.uround(m_radius.Value), agg_basics.uround(m_radius.Value)); } else { // True Gaussian Blur, 3-5 times slower than Stack Blur, // but still constant time of radius. Very sensitive // to precision, doubles are must here. //------------------ m_recursive_blur.blur(image2, m_radius.Value); } } } else { /* // Blur separate channels //------------------ if(m_channel_r.Checked) { typedef agg::pixfmt_alpha_blend_gray< agg::blender_gray8, agg::rendering_buffer, 3, 2> pixfmt_gray8r; pixfmt_gray8r pixf2r(m_rbuf2); if(pixf2r.attach(pixf, int(bbox.x1), int(bbox.y1), int(bbox.x2), int(bbox.y2))) { agg::stack_blur_gray8(pixf2r, agg::uround(m_radius.Value), agg::uround(m_radius.Value)); } } if(m_channel_g.Checked) { typedef agg::pixfmt_alpha_blend_gray< agg::blender_gray8, agg::rendering_buffer, 3, 1> pixfmt_gray8g; pixfmt_gray8g pixf2g(m_rbuf2); if(pixf2g.attach(pixf, int(bbox.x1), int(bbox.y1), int(bbox.x2), int(bbox.y2))) { agg::stack_blur_gray8(pixf2g, agg::uround(m_radius.Value), agg::uround(m_radius.Value)); } } if(m_channel_b.Checked) { typedef agg::pixfmt_alpha_blend_gray< agg::blender_gray8, agg::rendering_buffer, 3, 0> pixfmt_gray8b; pixfmt_gray8b pixf2b(m_rbuf2); if(pixf2b.attach(pixf, int(bbox.x1), int(bbox.y1), int(bbox.x2), int(bbox.y2))) { agg::stack_blur_gray8(pixf2b, agg::uround(m_radius.Value), agg::uround(m_radius.Value)); } } */ } double tm = stopwatch.ElapsedMilliseconds; // Render the shape itself //------------------ if (m_FlattenCurves.Checked) { m_ras.add_path(m_shape); } else { m_ras.add_path(m_path); } scanlineRenderer.RenderSolid(clippingProxy, m_ras, m_sl, new ColorF(0.6, 0.9, 0.7, 0.8).ToColor()); graphics2D.DrawString(string.Format("{0:F2} ms", tm), 140, 30); base.OnDraw(graphics2D); } [STAThread] public static void Main(string[] args) { var demoWidget = new blur(); var systemWindow = new SystemWindow(440, 330); systemWindow.Title = demoWidget.Title; systemWindow.AddChild(demoWidget); systemWindow.ShowAsSystemWindow(); } } }
// Copyright (c) 2014 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) // Parts based on code by MJ Hutchinson http://mjhutchinson.com/journal/2010/01/25/integrating_gtk_application_mac // Parts based on code by bugsnag-dotnet (https://github.com/bugsnag/bugsnag-dotnet/blob/v1.4/src/Bugsnag/Diagnostics.cs) using System; using System.Diagnostics; #if !NETSTANDARD2_0 using System.Management; #endif using System.Runtime.InteropServices; namespace SIL.PlatformUtilities { public static class Platform { private static bool? _isMono; private static string _sessionManager; public static bool IsUnix => Environment.OSVersion.Platform == PlatformID.Unix; public static bool IsWasta => IsUnix && System.IO.File.Exists("/etc/wasta-release"); public static bool IsCinnamon => IsUnix && (SessionManager.StartsWith("/usr/bin/cinnamon-session") || Environment.GetEnvironmentVariable("GDMSESSION") == "cinnamon"); public static bool IsMono { get { if (_isMono == null) _isMono = Type.GetType("Mono.Runtime") != null; return (bool)_isMono; } } public static bool IsDotNet => !IsMono; #if NETSTANDARD2_0 public static bool IsLinux => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); public static bool IsMac => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); public static bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); public static bool IsDotNetCore => RuntimeInformation.FrameworkDescription == ".NET Core"; public static bool IsDotNetFramework => IsDotNet && RuntimeInformation.FrameworkDescription == ".NET Framework"; #elif NET461 private static readonly string UnixNameMac = "Darwin"; private static readonly string UnixNameLinux = "Linux"; public static bool IsLinux => IsUnix && UnixName == UnixNameLinux; public static bool IsMac => IsUnix && UnixName == UnixNameMac; public static bool IsWindows => !IsUnix; public static bool IsDotNetCore => false; public static bool IsDotNetFramework => IsDotNet; private static string _unixName; private static string UnixName { get { if (_unixName == null) { IntPtr buf = IntPtr.Zero; try { buf = Marshal.AllocHGlobal(8192); // This is a hacktastic way of getting sysname from uname () if (uname(buf) == 0) _unixName = Marshal.PtrToStringAnsi(buf); } catch { _unixName = String.Empty; } finally { if (buf != IntPtr.Zero) Marshal.FreeHGlobal(buf); } } return _unixName; } } [DllImport("libc")] private static extern int uname(IntPtr buf); #endif /// <summary> /// On a Unix machine this gets the current desktop environment (gnome/xfce/...), on /// non-Unix machines the platform name. /// </summary> public static string DesktopEnvironment { get { if (!IsUnix) return Environment.OSVersion.Platform.ToString(); // see http://unix.stackexchange.com/a/116694 // and http://askubuntu.com/a/227669 string currentDesktop = Environment.GetEnvironmentVariable("XDG_CURRENT_DESKTOP"); if (string.IsNullOrEmpty(currentDesktop)) { var dataDirs = Environment.GetEnvironmentVariable("XDG_DATA_DIRS"); if (dataDirs != null) { dataDirs = dataDirs.ToLowerInvariant(); if (dataDirs.Contains("xfce")) currentDesktop = "XFCE"; else if (dataDirs.Contains("kde")) currentDesktop = "KDE"; else if (dataDirs.Contains("gnome")) currentDesktop = "Gnome"; } if (string.IsNullOrEmpty(currentDesktop)) currentDesktop = Environment.GetEnvironmentVariable("GDMSESSION") ?? string.Empty; } // Special case for Wasta 12 else if (currentDesktop == "GNOME" && Environment.GetEnvironmentVariable("GDMSESSION") == "cinnamon") currentDesktop = Environment.GetEnvironmentVariable("GDMSESSION"); else if (currentDesktop.ToLowerInvariant() == "ubuntu:gnome") currentDesktop = "gnome"; return currentDesktop?.ToLowerInvariant(); } } /// <summary> /// Get the currently running desktop environment (like Unity, Gnome shell etc) /// </summary> public static string DesktopEnvironmentInfoString { get { if (!IsUnix) return string.Empty; // see http://unix.stackexchange.com/a/116694 // and http://askubuntu.com/a/227669 var currentDesktop = DesktopEnvironment; var additionalInfo = string.Empty; var mirSession = Environment.GetEnvironmentVariable("MIR_SERVER_NAME"); if (!string.IsNullOrEmpty(mirSession)) additionalInfo = " [display server: Mir]"; var gdmSession = Environment.GetEnvironmentVariable("GDMSESSION") ?? "not set"; if (gdmSession.ToLowerInvariant().EndsWith("-wayland")) return $"{currentDesktop} ({gdmSession.Split('-')[0]} [display server: Wayland])"; return $"{currentDesktop} ({gdmSession}{additionalInfo})"; } } private static string SessionManager { get { if (_sessionManager == null) { IntPtr buf = IntPtr.Zero; try { // This is the only way I've figured out to get the session manager: read the // symbolic link destination value. buf = Marshal.AllocHGlobal(8192); var len = readlink("/etc/alternatives/x-session-manager", buf, 8192); if (len > 0) { // For some reason, Marshal.PtrToStringAnsi() sometimes returns null in Mono. // Copying the bytes and then converting them to a string avoids that problem. // Filenames are likely to be in UTF-8 on Linux if they are not pure ASCII. var bytes = new byte[len]; Marshal.Copy(buf, bytes, 0, len); _sessionManager = System.Text.Encoding.UTF8.GetString(bytes); } if (_sessionManager == null) _sessionManager = string.Empty; } catch { _sessionManager = string.Empty; } finally { if (buf != IntPtr.Zero) Marshal.FreeHGlobal(buf); } } return _sessionManager; } } [DllImport("libc")] private static extern int readlink(string path, IntPtr buf, int bufsiz); [DllImport("__Internal", EntryPoint = "mono_get_runtime_build_info")] private static extern string GetMonoVersion(); /// <summary> /// Gets the version of the currently running Mono (e.g. /// "5.0.1.1 (2017-02/5077205 Thu May 25 09:16:53 UTC 2017)"), or the empty string /// on Windows. /// </summary> public static string MonoVersion => IsMono ? GetMonoVersion() : string.Empty; /// <summary> /// Gets a string that describes the OS, e.g. 'Windows 10' or 'Ubuntu 16.04 LTS' /// </summary> /// <remarks>Note that you might have to add an app.config file to your executable /// that lists the supported Windows versions in order to get the correct Windows version /// reported (https://msdn.microsoft.com/en-us/library/windows/desktop/aa374191.aspx)! /// </remarks> public static string OperatingSystemDescription { get { switch (Environment.OSVersion.Platform) { // Platform is Windows 95, Windows 98, Windows 98 Second Edition, // or Windows Me. case PlatformID.Win32Windows: // Platform is Windows 95, Windows 98, Windows 98 Second Edition, // or Windows Me. switch (Environment.OSVersion.Version.Minor) { case 0: return "Windows 95"; case 10: return "Windows 98"; case 90: return "Windows Me"; default: return "UNKNOWN"; } case PlatformID.Win32NT: return GetWin32NTVersion(); case PlatformID.Unix: case PlatformID.MacOSX: return UnixOrMacVersion(); default: return "UNKNOWN"; } } } /// <summary> /// Detects the current operating system version if its Win32 NT /// </summary> /// <returns>The operation system version</returns> private static string GetWin32NTVersion() { switch (Environment.OSVersion.Version.Major) { case 3: return "Windows NT 3.51"; case 4: return "Windows NT 4.0"; case 5: return Environment.OSVersion.Version.Minor == 0 ? "Windows 2000" : "Windows XP"; case 6: switch (Environment.OSVersion.Version.Minor) { case 0: return "Windows Server 2008"; case 1: return IsWindowsServer ? "Windows Server 2008 R2" : "Windows 7"; case 2: return IsWindowsServer ? "Windows Server 2012" : "Windows 8"; case 3: return IsWindowsServer ? "Windows Server 2012 R2" : "Windows 8.1"; default: return "UNKNOWN"; } case 10: return "Windows 10"; default: return "UNKNOWN"; } } // https://stackoverflow.com/a/3138781/487503 private static bool IsWindowsServer => IsOS(OS_ANYSERVER); private const int OS_ANYSERVER = 29; [DllImport("shlwapi.dll", SetLastError=true)] private static extern bool IsOS(int os); /// <summary> /// Determines the OS version if on a UNIX based system /// </summary> /// <returns></returns> private static string UnixOrMacVersion() { if (RunTerminalCommand("uname") == "Darwin") { var osName = RunTerminalCommand("sw_vers", "-productName"); var osVersion = RunTerminalCommand("sw_vers", "-productVersion"); return osName + " (" + osVersion + ")"; } var distro = RunTerminalCommand("bash", "-c '[ $(which lsb_release) ] && [ -f /etc/wasta-release ] && echo \"$(lsb_release -d -s) ($(cat /etc/wasta-release | grep DESCRIPTION | cut -d\\\" -f 2))\" || lsb_release -d -s'"); return string.IsNullOrEmpty(distro) ? "UNIX" : distro; } /// <summary> /// Executes a command with arguments, used to send terminal commands in UNIX systems /// </summary> /// <param name="cmd">The command to send</param> /// <param name="args">The arguments to send</param> /// <returns>The returned output</returns> private static string RunTerminalCommand(string cmd, string args = null) { var proc = new Process { EnableRaisingEvents = false, StartInfo = { FileName = cmd, Arguments = args, UseShellExecute = false, RedirectStandardOutput = true } }; proc.Start(); proc.WaitForExit(); var output = proc.StandardOutput.ReadToEnd(); return output.Trim(); } public const string x64 = nameof(x64); public const string x86 = nameof(x86); public static string ProcessArchitecture => Environment.Is64BitProcess ? x64 : x86; public static bool IsRunning64Bit => Environment.Is64BitProcess; public static bool IsGnomeShell { get { if (!IsLinux) return false; var pids = RunTerminalCommand("pidof", "gnome-shell"); return !string.IsNullOrEmpty(pids); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: A wrapper class for the primitive type float. ** ** ===========================================================*/ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Single : IComparable, IConvertible, IFormattable, IComparable<Single>, IEquatable<Single> { private float m_value; // Do not rename (binary serialization) // // Public constants // public const float MinValue = (float)-3.40282346638528859e+38; public const float Epsilon = (float)1.4e-45; public const float MaxValue = (float)3.40282346638528859e+38; public const float PositiveInfinity = (float)1.0 / (float)0.0; public const float NegativeInfinity = (float)-1.0 / (float)0.0; public const float NaN = (float)0.0 / (float)0.0; // We use this explicit definition to avoid the confusion between 0.0 and -0.0. internal const float NegativeZero = (float)-0.0; /// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsFinite(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) < 0x7F800000; } /// <summary>Determines whether the specified value is infinite.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsInfinity(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) == 0x7F800000; } /// <summary>Determines whether the specified value is NaN.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNaN(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) > 0x7F800000; } /// <summary>Determines whether the specified value is negative.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNegative(float f) { var bits = unchecked((uint)BitConverter.SingleToInt32Bits(f)); return (bits & 0x80000000) == 0x80000000; } /// <summary>Determines whether the specified value is negative infinity.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNegativeInfinity(float f) { return (f == float.NegativeInfinity); } /// <summary>Determines whether the specified value is normal.</summary> [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsNormal(float f) { var bits = BitConverter.SingleToInt32Bits(f); bits &= 0x7FFFFFFF; return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) != 0); } /// <summary>Determines whether the specified value is positive infinity.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsPositiveInfinity(float f) { return (f == float.PositiveInfinity); } /// <summary>Determines whether the specified value is subnormal.</summary> [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsSubnormal(float f) { var bits = BitConverter.SingleToInt32Bits(f); bits &= 0x7FFFFFFF; return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) == 0); } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Single, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Single) { float f = (float)value; if (m_value < f) return -1; if (m_value > f) return 1; if (m_value == f) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(f) ? 0 : -1); else // f is NaN. return 1; } throw new ArgumentException(SR.Arg_MustBeSingle); } public int CompareTo(Single value) { if (m_value < value) return -1; if (m_value > value) return 1; if (m_value == value) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(value) ? 0 : -1); else // f is NaN. return 1; } [NonVersionable] public static bool operator ==(Single left, Single right) { return left == right; } [NonVersionable] public static bool operator !=(Single left, Single right) { return left != right; } [NonVersionable] public static bool operator <(Single left, Single right) { return left < right; } [NonVersionable] public static bool operator >(Single left, Single right) { return left > right; } [NonVersionable] public static bool operator <=(Single left, Single right) { return left <= right; } [NonVersionable] public static bool operator >=(Single left, Single right) { return left >= right; } public override bool Equals(Object obj) { if (!(obj is Single)) { return false; } float temp = ((Single)obj).m_value; if (temp == m_value) { return true; } return IsNaN(temp) && IsNaN(m_value); } public bool Equals(Single obj) { if (obj == m_value) { return true; } return IsNaN(obj) && IsNaN(m_value); } public unsafe override int GetHashCode() { float f = m_value; if (f == 0) { // Ensure that 0 and -0 have the same hash code return 0; } int v = *(int*)(&f); return v; } public override String ToString() { return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider)); } // Parses a float from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // public static float Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } public static float Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo); } public static float Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } public static float Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider)); } public static float Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider)); } public static Boolean TryParse(String s, out Single result) { if (s == null) { result = 0; return false; } return TryParse(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Single result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { result = 0; return false; } return TryParse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result); } public static Boolean TryParse(ReadOnlySpan<char> s, out Single result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static Boolean TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out Single result) { bool success = Number.TryParseSingle(s, style, info, out result); if (!success) { ReadOnlySpan<char> sTrim = s.Trim(); if (StringSpanHelpers.Equals(sTrim, info.PositiveInfinitySymbol)) { result = PositiveInfinity; } else if (StringSpanHelpers.Equals(sTrim, info.NegativeInfinitySymbol)) { result = NegativeInfinity; } else if (StringSpanHelpers.Equals(sTrim, info.NaNSymbol)) { result = NaN; } else { return false; // We really failed } } return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Single; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return m_value; } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// 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.ComponentModel; using System.Globalization; using System.IO; using System.Text; namespace System.Diagnostics { public partial class Process : IDisposable { /// <summary> /// Creates an array of <see cref="Process"/> components that are associated with process resources on a /// remote computer. These process resources share the specified process name. /// </summary> public static Process[] GetProcessesByName(string processName, string machineName) { ProcessManager.ThrowIfRemoteMachine(machineName); if (processName == null) { processName = string.Empty; } var reusableReader = new ReusableTextReader(); var processes = new List<Process>(); foreach (int pid in ProcessManager.EnumerateProcessIds()) { Interop.procfs.ParsedStat parsedStat; if (Interop.procfs.TryReadStatFile(pid, out parsedStat, reusableReader) && string.Equals(processName, parsedStat.comm, StringComparison.OrdinalIgnoreCase)) { ProcessInfo processInfo = ProcessManager.CreateProcessInfo(parsedStat, reusableReader); processes.Add(new Process(machineName, false, processInfo.ProcessId, processInfo)); } } return processes.ToArray(); } /// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary> public TimeSpan PrivilegedProcessorTime { get { return TicksToTimeSpan(GetStat().stime); } } /// <summary>Gets the time the associated process was started.</summary> internal DateTime StartTimeCore { get { return BootTimeToDateTime(TicksToTimeSpan(GetStat().starttime)); } } /// <summary>Computes a time based on a number of ticks since boot.</summary> /// <param name="timespanAfterBoot">The timespan since boot.</param> /// <returns>The converted time.</returns> internal static DateTime BootTimeToDateTime(TimeSpan timespanAfterBoot) { // Use the uptime and the current time to determine the absolute boot time. DateTime bootTime = DateTime.UtcNow - Uptime; // And use that to determine the absolute time for timespan. DateTime dt = bootTime + timespanAfterBoot; // The return value is expected to be in the local time zone. // It is converted here (rather than starting with DateTime.Now) to avoid DST issues. return dt.ToLocalTime(); } /// <summary>Gets the elapsed time since the system was booted.</summary> private static TimeSpan Uptime { get { // '/proc/uptime' accounts time a device spends in sleep mode. const string UptimeFile = Interop.procfs.ProcUptimeFilePath; string text = File.ReadAllText(UptimeFile); double uptimeSeconds = 0; int length = text.IndexOf(' '); if (length != -1) { Double.TryParse(text.AsSpan().Slice(0, length), NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out uptimeSeconds); } return TimeSpan.FromSeconds(uptimeSeconds); } } /// <summary>Gets execution path</summary> private string GetPathToOpenFile() { string[] allowedProgramsToRun = { "xdg-open", "gnome-open", "kfmclient" }; foreach (var program in allowedProgramsToRun) { string pathToProgram = FindProgramInPath(program); if (!string.IsNullOrEmpty(pathToProgram)) { return pathToProgram; } } return null; } /// <summary> /// Gets the amount of time the associated process has spent utilizing the CPU. /// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and /// <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>. /// </summary> public TimeSpan TotalProcessorTime { get { Interop.procfs.ParsedStat stat = GetStat(); return TicksToTimeSpan(stat.utime + stat.stime); } } /// <summary> /// Gets the amount of time the associated process has spent running code /// inside the application portion of the process (not the operating system core). /// </summary> public TimeSpan UserProcessorTime { get { return TicksToTimeSpan(GetStat().utime); } } partial void EnsureHandleCountPopulated() { if (_processInfo.HandleCount <= 0 && _haveProcessId) { string path = Interop.procfs.GetFileDescriptorDirectoryPathForProcess(_processId); if (Directory.Exists(path)) { try { _processInfo.HandleCount = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly).Length; } catch (DirectoryNotFoundException) // Occurs when the process is deleted between the Exists check and the GetFiles call. { } } } } /// <summary> /// Gets or sets which processors the threads in this process can be scheduled to run on. /// </summary> private unsafe IntPtr ProcessorAffinityCore { get { EnsureState(State.HaveId); IntPtr set; if (Interop.Sys.SchedGetAffinity(_processId, out set) != 0) { throw new Win32Exception(); // match Windows exception } return set; } set { EnsureState(State.HaveId); if (Interop.Sys.SchedSetAffinity(_processId, ref value) != 0) { throw new Win32Exception(); // match Windows exception } } } /// <summary> /// Make sure we have obtained the min and max working set limits. /// </summary> private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet) { minWorkingSet = IntPtr.Zero; // no defined limit available ulong rsslim = GetStat().rsslim; // rsslim is a ulong, but maxWorkingSet is an IntPtr, so we need to cap rsslim // at the max size of IntPtr. This often happens when there is no configured // rsslim other than ulong.MaxValue, which without these checks would show up // as a maxWorkingSet == -1. switch (IntPtr.Size) { case 4: if (rsslim > int.MaxValue) rsslim = int.MaxValue; break; case 8: if (rsslim > long.MaxValue) rsslim = long.MaxValue; break; } maxWorkingSet = (IntPtr)rsslim; } /// <summary>Sets one or both of the minimum and maximum working set limits.</summary> /// <param name="newMin">The new minimum working set limit, or null not to change it.</param> /// <param name="newMax">The new maximum working set limit, or null not to change it.</param> /// <param name="resultingMin">The resulting minimum working set limit after any changes applied.</param> /// <param name="resultingMax">The resulting maximum working set limit after any changes applied.</param> private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax) { // RLIMIT_RSS with setrlimit not supported on Linux > 2.4.30. throw new PlatformNotSupportedException(SR.MinimumWorkingSetNotSupported); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary>Gets the path to the executable for the process, or null if it could not be retrieved.</summary> /// <param name="processId">The pid for the target process, or -1 for the current process.</param> internal static string GetExePath(int processId = -1) { string exeFilePath = processId == -1 ? Interop.procfs.SelfExeFilePath : Interop.procfs.GetExeFilePathForProcess(processId); return Interop.Sys.ReadLink(exeFilePath); } // ---------------------------------- // ---- Unix PAL layer ends here ---- // ---------------------------------- /// <summary>Reads the stats information for this process from the procfs file system.</summary> private Interop.procfs.ParsedStat GetStat() { EnsureState(State.HaveId); Interop.procfs.ParsedStat stat; if (!Interop.procfs.TryReadStatFile(_processId, out stat, new ReusableTextReader())) { throw new Win32Exception(SR.ProcessInformationUnavailable); } return stat; } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Conditions { using System; using System.Runtime.InteropServices; using System.Text.RegularExpressions; /// <summary> /// A bunch of utility methods (mostly predicates) which can be used in /// condition expressions. Partially inspired by XPath 1.0. /// </summary> [ConditionMethods] public static class ConditionMethods { /// <summary> /// Compares two values for equality. /// </summary> /// <param name="firstValue">The first value.</param> /// <param name="secondValue">The second value.</param> /// <returns><b>true</b> when two objects are equal, <b>false</b> otherwise.</returns> [ConditionMethod("equals")] public static bool Equals2(object firstValue, object secondValue) { return firstValue.Equals(secondValue); } /// <summary> /// Compares two strings for equality. /// </summary> /// <param name="firstValue">The first string.</param> /// <param name="secondValue">The second string.</param> /// <param name="ignoreCase">Optional. If <c>true</c>, case is ignored; if <c>false</c> (default), case is significant.</param> /// <returns><b>true</b> when two strings are equal, <b>false</b> otherwise.</returns> [ConditionMethod("strequals")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Not called directly, only ever Invoked.")] #if SILVERLIGHT public static bool Equals2(string firstValue, string secondValue, [Optional] object ignoreCase) #else public static bool Equals2( string firstValue, string secondValue, [Optional, DefaultParameterValue(false)] bool ignoreCase) #endif { #if SILVERLIGHT bool ic = false; if (ignoreCase is bool b) ic = b; #else bool ic = ignoreCase; #endif return firstValue.Equals(secondValue, ic ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } /// <summary> /// Gets or sets a value indicating whether the second string is a substring of the first one. /// </summary> /// <param name="haystack">The first string.</param> /// <param name="needle">The second string.</param> /// <param name="ignoreCase">Optional. If <c>true</c> (default), case is ignored; if <c>false</c>, case is significant.</param> /// <returns><b>true</b> when the second string is a substring of the first string, <b>false</b> otherwise.</returns> [ConditionMethod("contains")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Not called directly, only ever Invoked.")] #if SILVERLIGHT public static bool Contains( string haystack, string needle, [Optional] object ignoreCase) #else public static bool Contains(string haystack, string needle, [Optional, DefaultParameterValue(true)] bool ignoreCase) #endif { #if SILVERLIGHT bool ic = true; if ( ignoreCase != null && ignoreCase is bool ) ic = ( bool ) ignoreCase; #else bool ic = ignoreCase; #endif return haystack.IndexOf(needle, ic ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) >= 0; } /// <summary> /// Gets or sets a value indicating whether the second string is a prefix of the first one. /// </summary> /// <param name="haystack">The first string.</param> /// <param name="needle">The second string.</param> /// <param name="ignoreCase">Optional. If <c>true</c> (default), case is ignored; if <c>false</c>, case is significant.</param> /// <returns><b>true</b> when the second string is a prefix of the first string, <b>false</b> otherwise.</returns> [ConditionMethod("starts-with")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Not called directly, only ever Invoked.")] #if SILVERLIGHT public static bool StartsWith( string haystack, string needle, [Optional] object ignoreCase) #else public static bool StartsWith(string haystack, string needle, [Optional, DefaultParameterValue(true)] bool ignoreCase) #endif { #if SILVERLIGHT bool ic = true; if ( ignoreCase != null && ignoreCase is bool ) ic = ( bool ) ignoreCase; #else bool ic = ignoreCase; #endif return haystack.StartsWith(needle, ic ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } /// <summary> /// Gets or sets a value indicating whether the second string is a suffix of the first one. /// </summary> /// <param name="haystack">The first string.</param> /// <param name="needle">The second string.</param> /// <param name="ignoreCase">Optional. If <c>true</c> (default), case is ignored; if <c>false</c>, case is significant.</param> /// <returns><b>true</b> when the second string is a prefix of the first string, <b>false</b> otherwise.</returns> [ConditionMethod("ends-with")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Not called directly, only ever Invoked.")] #if SILVERLIGHT public static bool EndsWith( string haystack, string needle, [Optional] object ignoreCase) #else public static bool EndsWith(string haystack, string needle, [Optional, DefaultParameterValue(true)] bool ignoreCase) #endif { #if SILVERLIGHT bool ic = true; if ( ignoreCase != null && ignoreCase is bool ) ic = ( bool ) ignoreCase; #else bool ic = ignoreCase; #endif return haystack.EndsWith(needle, ic ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } /// <summary> /// Returns the length of a string. /// </summary> /// <param name="text">A string whose lengths is to be evaluated.</param> /// <returns>The length of the string.</returns> [ConditionMethod("length")] public static int Length(string text) { return text.Length; } /// <summary> /// Indicates whether the specified regular expression finds a match in the specified input string. /// </summary> /// <param name="input">The string to search for a match.</param> /// <param name="pattern">The regular expression pattern to match.</param> /// <param name="options">A string consisting of the desired options for the test. The possible values are those of the <see cref="RegexOptions"/> separated by commas.</param> /// <returns>true if the regular expression finds a match; otherwise, false.</returns> [ConditionMethod("regex-matches")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Not called directly, only ever Invoked.")] #if SILVERLIGHT public static bool RegexMatches(string input, string pattern, [Optional] string options) #else public static bool RegexMatches(string input, string pattern, [Optional, DefaultParameterValue("")] string options) #endif { RegexOptions regexOpts = ParseRegexOptions(options); return Regex.IsMatch(input, pattern, regexOpts); } /// <summary> /// /// </summary> /// <param name="options"></param> /// <returns></returns> private static RegexOptions ParseRegexOptions(string options) { if (string.IsNullOrEmpty(options)) { return RegexOptions.None; } return (RegexOptions)Enum.Parse(typeof(RegexOptions), options, true); } } }
using System.Collections.Generic; using System.Text.RegularExpressions; using System.IO; using System.Linq; using System; namespace MixpanelSDK.UnityEditor.iOS.Xcode.PBX { enum TokenType { EOF, Invalid, String, QuotedString, Comment, Semicolon, // ; Comma, // , Eq, // = LParen, // ( RParen, // ) LBrace, // { RBrace, // } } class Token { public TokenType type; // the line of the input stream the token starts in (0-based) public int line; // start and past-the-end positions of the token in the input stream public int begin, end; } class TokenList : List<Token> { } class Lexer { string text; int pos; int length; int line; public static TokenList Tokenize(string text) { var lexer = new Lexer(); lexer.SetText(text); return lexer.ScanAll(); } public void SetText(string text) { this.text = text + " "; // to prevent out-of-bounds access during look ahead pos = 0; length = text.Length; line = 0; } public TokenList ScanAll() { var tokens = new TokenList(); while (true) { var tok = new Token(); ScanOne(tok); tokens.Add(tok); if (tok.type == TokenType.EOF) break; } return tokens; } void UpdateNewlineStats(char ch) { if (ch == '\n') line++; } // tokens list is modified in the case when we add BrokenLine token and need to remove already // added tokens for the current line void ScanOne(Token tok) { while (true) { while (pos < length && Char.IsWhiteSpace(text[pos])) { UpdateNewlineStats(text[pos]); pos++; } if (pos >= length) { tok.type = TokenType.EOF; break; } char ch = text[pos]; char ch2 = text[pos+1]; if (ch == '\"') ScanQuotedString(tok); else if (ch == '/' && ch2 == '*') ScanMultilineComment(tok); else if (ch == '/' && ch2 == '/') ScanComment(tok); else if (IsOperator(ch)) ScanOperator(tok); else ScanString(tok); // be more robust and accept whatever is left return; } } void ScanString(Token tok) { tok.type = TokenType.String; tok.begin = pos; while (pos < length) { char ch = text[pos]; char ch2 = text[pos+1]; if (Char.IsWhiteSpace(ch)) break; else if (ch == '\"') break; else if (ch == '/' && ch2 == '*') break; else if (ch == '/' && ch2 == '/') break; else if (IsOperator(ch)) break; pos++; } tok.end = pos; tok.line = line; } void ScanQuotedString(Token tok) { tok.type = TokenType.QuotedString; tok.begin = pos; pos++; while (pos < length) { // ignore escaped quotes if (text[pos] == '\\' && text[pos+1] == '\"') { pos += 2; continue; } // note that we close unclosed quotes if (text[pos] == '\"') break; UpdateNewlineStats(text[pos]); pos++; } pos++; tok.end = pos; tok.line = line; } void ScanMultilineComment(Token tok) { tok.type = TokenType.Comment; tok.begin = pos; pos += 2; while (pos < length) { if (text[pos] == '*' && text[pos+1] == '/') break; // we support multiline comments UpdateNewlineStats(text[pos]); pos++; } pos += 2; tok.end = pos; tok.line = line; } void ScanComment(Token tok) { tok.type = TokenType.Comment; tok.begin = pos; pos += 2; while (pos < length) { if (text[pos] == '\n') break; pos++; } UpdateNewlineStats(text[pos]); pos++; tok.end = pos; tok.line = line; } bool IsOperator(char ch) { if (ch == ';' || ch == ',' || ch == '=' || ch == '(' || ch == ')' || ch == '{' || ch == '}') return true; return false; } void ScanOperator(Token tok) { switch (text[pos]) { case ';': ScanOperatorSpecific(tok, TokenType.Semicolon); return; case ',': ScanOperatorSpecific(tok, TokenType.Comma); return; case '=': ScanOperatorSpecific(tok, TokenType.Eq); return; case '(': ScanOperatorSpecific(tok, TokenType.LParen); return; case ')': ScanOperatorSpecific(tok, TokenType.RParen); return; case '{': ScanOperatorSpecific(tok, TokenType.LBrace); return; case '}': ScanOperatorSpecific(tok, TokenType.RBrace); return; default: return; } } void ScanOperatorSpecific(Token tok, TokenType type) { tok.type = type; tok.begin = pos; pos++; tok.end = pos; tok.line = line; } } } // namespace MixpanelSDK.UnityEditor.iOS.Xcode
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace CPV.Data.Migrations { public partial class CreateIdentitySchema : 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>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); }); 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>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), LockoutEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, 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>(maxLength: 256, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); 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_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_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_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_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_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_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_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName"); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_UserId", table: "AspNetUserRoles", column: "UserId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Shouldly; using XlsToEf.Import; using XlsToEf.Tests.ImportHelperFiles; using XlsToEf.Tests.Models; namespace XlsToEf.Tests { public class XlsxToTableImporterDbTests : DbTestBase { public async Task Should_Import_Column_data_into_db_from_excel() { var objectToUpdate = new Order { Id = 346, OrderDate = DateTime.Today, }; PersistToDatabase(objectToUpdate); var excelIoWrapper = new FakeExcelIo(); var importer = new XlsxToTableImporter(GetDb(), excelIoWrapper); var order = new Order(); var importMatchingData = new DataMatchesForImportingOrderData { FileName = "foo.xlsx", Sheet = "mysheet", Selected = new List<XlsToEfColumnPair> { XlsToEfColumnPair.Create(() => order.Id, "xlsCol5"), XlsToEfColumnPair.Create("OrderDate", "xlsCol2"), XlsToEfColumnPair.Create(() => order.DeliveryDate, "xlsCol4"), }, }; await importer.ImportColumnData<Order>(importMatchingData); var updatedItem = GetDb().Set<Order>().First(); updatedItem.OrderDate.ShouldBe(new DateTime(2014, 8, 15)); updatedItem.DeliveryDate.ShouldBe(new DateTime(2015, 9, 22)); } public async Task Should_Import_new_Column_data_into_db_from_excel() { var excelIoWrapper = new FakeExcelIo(); var importer = new XlsxToTableImporter(GetDb(), excelIoWrapper); var order = new Order(); var importMatchingData = new DataMatchesForImportingOrderData { FileName = "foo.xlsx", Sheet = "mysheet", Selected = new List<XlsToEfColumnPair> { XlsToEfColumnPair.Create(() => order.Id, "xlsCol5"), XlsToEfColumnPair.Create("OrderDate", "xlsCol2"), XlsToEfColumnPair.Create(() => order.DeliveryDate, "xlsCol4"), }, }; await importer.ImportColumnData<Order>(importMatchingData, saveBehavior:new ImportSaveBehavior { RecordMode = RecordMode.Upsert}); var updatedItem = GetDb().Set<Order>().First(); updatedItem.OrderDate.ShouldBe(new DateTime(2014, 8, 15)); updatedItem.DeliveryDate.ShouldBe(new DateTime(2015, 9, 22)); } public async Task Should_report_bad_data_and_save_good_data_with_only_updates_allowed() { var objectToUpdate = new Order { Id = 346, OrderDate = new DateTime(2009, 1, 5), DeliveryDate = new DateTime(2010, 5, 7) }; PersistToDatabase(objectToUpdate); var excelIoWrapper = new FakeExcelIo(); var badRowIdDoesNotExist = new Dictionary<string, string> { {"xlsCol5", "999"}, {"xlsCol2", "12/16/2016"}, {"xlsCol4", "8/1/2014"} }; excelIoWrapper.Rows.Add(badRowIdDoesNotExist); var dbContext = GetDb(); var importer = new XlsxToTableImporter(dbContext, excelIoWrapper); var order = new Order(); var importMatchingData = new DataMatchesForImportingOrderData { FileName = "foo.xlsx", Sheet = "mysheet", Selected = new List<XlsToEfColumnPair> { XlsToEfColumnPair.Create(() => order.Id, "xlsCol5"), XlsToEfColumnPair.Create("OrderDate", "xlsCol2"), XlsToEfColumnPair.Create(() => order.DeliveryDate, "xlsCol4"), }, }; var results = await importer.ImportColumnData<Order>(importMatchingData, new ImportSaveBehavior { RecordMode= RecordMode.UpdateOnly}); results.SuccessCount.ShouldBe(1); results.RowErrorDetails.Count.ShouldBe(1); var dbSet = dbContext.Set<Order>().ToArray(); dbSet.Length.ShouldBe(1); var entity = dbSet.First(); entity.DeliveryDate.ShouldBe(DateTime.Parse("9/22/2015")); } public async Task Should_report_bad_data_and_save_good_data_with_only_updates_allowed_incremental_saves() { var objectToUpdate = new Order { Id = 346, OrderDate = new DateTime(2009, 1, 5), DeliveryDate = new DateTime(2010, 5, 7) }; PersistToDatabase(objectToUpdate); var excelIoWrapper = new FakeExcelIo(); var badRowIdDoesNotExist = new Dictionary<string, string> { {"xlsCol5", "999"}, {"xlsCol2", "12/16/2016"}, {"xlsCol4", "8/1/2014"} }; excelIoWrapper.Rows.Add(badRowIdDoesNotExist); var dbContext = GetDb(); var importer = new XlsxToTableImporter(dbContext, excelIoWrapper); var order = new Order(); var importMatchingData = new DataMatchesForImportingOrderData { FileName = "foo.xlsx", Sheet = "mysheet", Selected = new List<XlsToEfColumnPair> { XlsToEfColumnPair.Create(() => order.Id, "xlsCol5"), XlsToEfColumnPair.Create("OrderDate", "xlsCol2"), XlsToEfColumnPair.Create(() => order.DeliveryDate, "xlsCol4"), }, }; var results = await importer.ImportColumnData<Order>(importMatchingData, new ImportSaveBehavior { RecordMode = RecordMode.UpdateOnly, CommitMode = CommitMode.AnySuccessfulOneAtATime }); results.SuccessCount.ShouldBe(1); results.RowErrorDetails.Count.ShouldBe(1); var dbSet = dbContext.Set<Order>().ToArray(); dbSet.Length.ShouldBe(1); var entity = dbSet.First(); entity.DeliveryDate.ShouldBe(DateTime.Parse("9/22/2015")); } public async Task Should_reject_all_changes_if_all_or_nothing_and_encounters_error() { var originalOrderDate = new DateTime(2009, 1, 5); var originalDeliveryDate = new DateTime(2010, 5, 7); var objectToUpdate = new Order { Id = 346, OrderDate = originalOrderDate, DeliveryDate = originalDeliveryDate }; PersistToDatabase(objectToUpdate); var excelIoWrapper = new FakeExcelIo(); var badRowIdDoesNotExist = new Dictionary<string, string> { {"xlsCol5", "999"}, {"xlsCol2", "12/16/2016"}, {"xlsCol4", "8/1/2014"} }; excelIoWrapper.Rows.Add(badRowIdDoesNotExist); var dbContext = GetDb(); var importer = new XlsxToTableImporter(dbContext, excelIoWrapper); var order = new Order(); var importMatchingData = new DataMatchesForImportingOrderData { FileName = "foo.xlsx", Sheet = "mysheet", Selected = new List<XlsToEfColumnPair> { XlsToEfColumnPair.Create(() => order.Id, "xlsCol5"), XlsToEfColumnPair.Create("OrderDate", "xlsCol2"), XlsToEfColumnPair.Create(() => order.DeliveryDate, "xlsCol4"), }, }; var results = await importer.ImportColumnData<Order>(importMatchingData, new ImportSaveBehavior { RecordMode = RecordMode.CreateOnly, CommitMode = CommitMode.CommitAllAtEndIfAllGoodOrRejectAll }); results.SuccessCount.ShouldBe(1); results.RowErrorDetails.Count.ShouldBe(1); var dbSet = dbContext.Set<Order>().ToArray(); dbSet.Count().ShouldBe(1); dbSet .Any(x => x.DeliveryDate == originalDeliveryDate && x.OrderDate == originalOrderDate) .ShouldBe(true); } public async Task Should_Import_Column_data_matching_nullable_column_without_error() { var objectToUpdate = new Order { Id = 346, OrderDate = DateTime.Today, DeliveryDate = null, }; PersistToDatabase(objectToUpdate); var excelIoWrapper = new FakeExcelIo(); var importer = new XlsxToTableImporter(GetDb(), excelIoWrapper); var order = new Order(); var importMatchingData = new DataMatchesForImportingOrderData { FileName = "foo.xlsx", Sheet = "mysheet", Selected = new List<XlsToEfColumnPair> { XlsToEfColumnPair.Create(() => order.Id, "xlsCol5"), XlsToEfColumnPair.Create(() => order.DeliveryDate, "xlsCol2"), }, }; await importer.ImportColumnData<Order>(importMatchingData); var updatedItem = GetDb().Set<Order>().First(); updatedItem.DeliveryDate.ShouldBe(new DateTime(2014, 8, 15)); } public async Task Should_Import_rows_using_non_id_column() { var addressLine1 = "111 Oak Street"; var objectToUpdate = new Address { AddrId = "123456", AddressLine1 = addressLine1 }; PersistToDatabase(objectToUpdate); var excelIoWrapper = new FakeExcelIo(); var importer = new XlsxToTableImporter(GetDb(), excelIoWrapper); var addr = new Address(); var importMatchingData = new DataMatchesForImportingAddressData { FileName = "foo.xlsx", Sheet = "mysheet", Selected = new List<XlsToEfColumnPair> { XlsToEfColumnPair.Create(() => addr.AddrId, "xlsCol6"), XlsToEfColumnPair.Create(() => addr.AddressLine1, "xlsCol2"), }, }; await importer.ImportColumnData<Address>(importMatchingData); var updatedItem = GetDb().Set<Address>().First(); updatedItem.AddressLine1.ShouldBe("8/15/2014"); updatedItem.AddrId.ShouldBe("123456"); } public async Task Should_Import_new_rows_with_generated_id_entity_createonly() { var excelIoWrapper = new FakeExcelIo(); var importer = new XlsxToTableImporter(GetDb(), excelIoWrapper); var cat = new ProductCategory(); var importMatchingData = new DataMatchesForImportingProductData { FileName = "foo.xlsx", Sheet = "mysheet", Selected = new List<XlsToEfColumnPair> { XlsToEfColumnPair.Create(() => cat.CategoryCode, "xlsCol8"), XlsToEfColumnPair.Create("CategoryName", "xlsCol7"), }, }; Func<string, Expression<Func<ProductCategory, bool>>> selectorFinder = (y) => z => z.Id == int.Parse(y); await importer.ImportColumnData(importMatchingData, finder: selectorFinder, saveBehavior: new ImportSaveBehavior { RecordMode=RecordMode.CreateOnly}); var updatedItem = GetDb().Set<ProductCategory>().First(); updatedItem.CategoryCode.ShouldBe("FRZ"); updatedItem.CategoryName.ShouldBe("Frozen Food"); } public async Task Should_Import_new_and_update_rows_with_generated_id_entity_upsert() { var objectToUpdate = new ProductCategory { CategoryCode = "AAA", CategoryName = "BBB" }; PersistToDatabase(objectToUpdate); var excelIoWrapper = new FakeExcelIo(); var importer = new XlsxToTableImporter(GetDb(), excelIoWrapper); var cat = new ProductCategory(); var importMatchingData = new DataMatchesForImportingProductData { FileName = "foo.xlsx", Sheet = "mysheet", Selected = new List<XlsToEfColumnPair> { XlsToEfColumnPair.Create(() => cat.Id, "xlsCol6"), XlsToEfColumnPair.Create("CategoryCode", "xlsCol8"), XlsToEfColumnPair.Create(() => cat.CategoryName, "xlsCol7"), }, }; var id = objectToUpdate.Id; excelIoWrapper.Rows[0]["xlsCol6"] = id.ToString(); // change the id to the autogenerated one so we can update it. excelIoWrapper.Rows.Add( new Dictionary<string, string> { {"xlsCol5", "347"}, {"xlsCol1", "56493.7"}, {"xlsCol2", "8/16/2014"}, {"xlsCol3", "8888.5"}, {"xlsCol4", "9/27/2015"}, {"xlsCol6", ""}, {"xlsCol7", "Vegetables"}, {"xlsCol8", "VEG"}, }); Func<string, Expression<Func<ProductCategory, bool>>> selectorFinder = (y) => z => z.Id == int.Parse(y); await importer.ImportColumnData<ProductCategory>(importMatchingData); var updatedItem = GetDb().Set<ProductCategory>().First(x => x.Id == id); updatedItem.CategoryCode.ShouldBe("FRZ"); updatedItem.CategoryName.ShouldBe("Frozen Food"); var newItem = GetDb().Set<ProductCategory>().First(x => x.CategoryCode == "VEG"); newItem.CategoryName.ShouldBe("Vegetables"); } public async Task Should_update_rows_with_generated_id_entity_update() { var objectToUpdate = new ProductCategory { CategoryCode = "AAA", CategoryName = "BBB" }; PersistToDatabase(objectToUpdate); var excelIoWrapper = new FakeExcelIo(); var importer = new XlsxToTableImporter(GetDb(), excelIoWrapper); var cat = new ProductCategory(); var importMatchingData = new DataMatchesForImportingProductData { FileName = "foo.xlsx", Sheet = "mysheet", Selected = new List<XlsToEfColumnPair> { XlsToEfColumnPair.Create(() => cat.Id, "xlsCol6"), XlsToEfColumnPair.Create("CategoryCode", "xlsCol8"), XlsToEfColumnPair.Create(() => cat.CategoryName, "xlsCol7"), }, }; var id = objectToUpdate.Id; excelIoWrapper.Rows[0]["xlsCol6"] = id.ToString(); // change the id to the autogenerated one so we can update it. await importer.ImportColumnData<ProductCategory>(importMatchingData, saveBehavior: new ImportSaveBehavior { RecordMode= RecordMode.UpdateOnly}); var updatedItem = GetDb().Set<ProductCategory>().First(x => x.Id == id); updatedItem.CategoryCode.ShouldBe("FRZ"); updatedItem.CategoryName.ShouldBe("Frozen Food"); } public async Task Should_Use_Validator() { var orderDate = DateTime.Today; var objectToUpdate = new Order { Id = 346, OrderDate = orderDate, }; PersistToDatabase(objectToUpdate); var excelIoWrapper = new FakeExcelIo(); var importer = new XlsxToTableImporter(GetDb(), excelIoWrapper); var order = new Order(); var importMatchingData = new DataMatchesForImportingOrderData { FileName = "foo.xlsx", Sheet = "mysheet", Selected = new List<XlsToEfColumnPair> { XlsToEfColumnPair.Create(() => order.Id, "xlsCol5"), XlsToEfColumnPair.Create("OrderDate", "xlsCol2"), XlsToEfColumnPair.Create(() => order.DeliveryDate, "xlsCol4"), }, }; var orderValidator = new TestValidator(); var result = await importer.ImportColumnData<Order, int>(importMatchingData, validator: orderValidator); var valueCollection = result.RowErrorDetails.Values; valueCollection.Count.ShouldBe(1); valueCollection.First().ShouldContain("Order Date"); var updatedItem = GetDb().Set<Order>().First(); updatedItem.OrderDate.ShouldBe(orderDate); updatedItem.DeliveryDate.ShouldBeNull(); } public async Task Should_Import_from_non_tempfile_new_rows_with_generated_id_entity_createonly() { var excelIoWrapper = new FakeExcelIo(); var importer = new XlsxToTableImporter(GetDb(), excelIoWrapper); var cat = new ProductCategory(); var importMatchingData = new DataMatchesForImportingProductData { FileName = "foo.xlsx", Sheet = "mysheet", Selected = new List<XlsToEfColumnPair> { XlsToEfColumnPair.Create(() => cat.CategoryCode, "xlsCol8"), XlsToEfColumnPair.Create("CategoryName", "xlsCol7"), }, }; Func<string, Expression<Func<ProductCategory, bool>>> selectorFinder = (y) => z => z.Id == int.Parse(y); var fileLocation = @"c:\myfiles\"; await importer.ImportColumnData(importMatchingData, finder: selectorFinder, saveBehavior: new ImportSaveBehavior { RecordMode = RecordMode.CreateOnly }, fileLocation: fileLocation); var updatedItem = GetDb().Set<ProductCategory>().First(); updatedItem.CategoryCode.ShouldBe("FRZ"); updatedItem.CategoryName.ShouldBe("Frozen Food"); excelIoWrapper.FileName.ShouldBe(fileLocation + importMatchingData.FileName); } private class TestValidator : IEntityValidator<Order> { public Dictionary<string, string> GetValidationErrors(Order entity) { var errors = new Dictionary<string, string>(); if (entity.OrderDate == new DateTime(2014, 8, 15)) { errors.Add("Order Date", "That is not a valid date in the system"); } return errors; } } public async Task Should_Return_No_Validation_Errors() { var orderDate = DateTime.Today; var objectToUpdate = new Order { Id = 346, OrderDate = orderDate, }; PersistToDatabase(objectToUpdate); var excelIoWrapper = new FakeExcelIo(); var importer = new XlsxToTableImporter(GetDb(), excelIoWrapper); var order = new Order(); var importMatchingData = new DataMatchesForImportingOrderData { FileName = "foo.xlsx", Sheet = "mysheet", Selected = new List<XlsToEfColumnPair> { XlsToEfColumnPair.Create(() => order.Id, "xlsCol5"), XlsToEfColumnPair.Create("OrderDate", "xlsCol2"), XlsToEfColumnPair.Create(() => order.DeliveryDate, "xlsCol4"), }, }; var orderValidator = new EmptyTestValidator(); var result = await importer.ImportColumnData<Order, int>(importMatchingData, validator: orderValidator); var valueCollection = result.RowErrorDetails.Values; valueCollection.Count.ShouldBe(0); } private class EmptyTestValidator : IEntityValidator<Order> { public Dictionary<string, string> GetValidationErrors(Order entity) { return new Dictionary<string, string>(); } } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace FileSystemTest { public class RWAllBytes : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); Directory.CreateDirectory(testDir); Directory.SetCurrentDirectory(testDir); } catch (Exception ex) { Log.Comment("Skipping: Unable to initialize file system" + ex.Message); return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region Local vars private const string file1Name = "file1.tmp"; private const string file2Name = "file2.txt"; private const string testDir = "ReadAllBytes"; #endregion Local vars #region Test Cases [TestMethod] public MFTestResults InvalidArguments() { MFTestResults result = MFTestResults.Pass; byte[] file = null; try { try { Log.Comment("ReadAllBytes Null"); file = File.ReadAllBytes(null); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("ReadAllBytes String.Empty"); file = File.ReadAllBytes(String.Empty); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("ReadAllBytes White Space"); file = File.ReadAllBytes(" "); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("WriteAllBytes Null path"); File.WriteAllBytes(null, new byte[10]); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("WriteAllBytes Null bytes"); File.WriteAllBytes(file1Name, null); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("WriteAllBytes String.Empty path"); File.WriteAllBytes(String.Empty, new byte[20]); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("WriteAllBytes White Space path"); File.WriteAllBytes(" ", new byte[30]); Log.Exception( "Expected ArgumentException, but got " + file.Length ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults IOExceptionTests() { MFTestResults result = MFTestResults.Pass; new FileStream(file1Name, FileMode.Create); Log.Comment("Current Directory: " + Directory.GetCurrentDirectory()); try { try { Log.Comment("non-existent file"); File.ReadAllBytes("non-existent.file"); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); result = MFTestResults.Pass; } try { Log.Comment("ReadOnly file"); File.SetAttributes(file1Name, FileAttributes.ReadOnly); File.WriteAllBytes(file1Name, new byte[4]); Log.Exception( "Expected IOException" ); return MFTestResults.Fail; } catch (IOException ioe2) { /// Validate IOException.ErrorCode. Log.Comment( "Got correct exception: " + ioe2.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCase() { MFTestResults result = MFTestResults.Pass; byte[] writebytes; byte[] readbytes; try { // Clean up if (File.Exists(file2Name)) File.Delete(file2Name); Log.Comment("Create 0 length file"); File.Create(file2Name).Close(); Log.Comment("Read all bytes - expect 0"); readbytes = File.ReadAllBytes(file2Name); if (readbytes.Length != 0) { Log.Exception( "Got " + readbytes.Length + " bytes!" ); return MFTestResults.Fail; } Log.Comment("Write bytes 0-255 to file"); writebytes = new byte[256]; for (int i = 0; i < writebytes.Length; i++) { writebytes[i] = (byte)i; } File.WriteAllBytes(file2Name, writebytes); Log.Comment("Read all bytes - expect 256"); readbytes = File.ReadAllBytes(file2Name); if (readbytes.Length != writebytes.Length) { Log.Exception( "Read unexpected number of bytes: " + readbytes.Length ); return MFTestResults.Fail; } for (int i = 0; i < readbytes.Length; i++) { if (readbytes[i] != i) { Log.Exception( "Expected byte " + i + " but got byte " + readbytes[i] ); return MFTestResults.Fail; } } Log.Comment("Write again, 255-0"); writebytes = new byte[256]; for (int i = 0; i < writebytes.Length; i++) { writebytes[i] = (byte)~(i); } File.WriteAllBytes(file2Name, writebytes); Log.Comment("Read all bytes - expect 256"); readbytes = File.ReadAllBytes(file2Name); if (readbytes.Length != writebytes.Length) { Log.Exception( "Read unexpected number of bytes: " + readbytes.Length ); return MFTestResults.Fail; } for (int i = 0; i < readbytes.Length; i++) { if (readbytes[i] != (byte)~(i)) { Log.Exception( "Expected byte " + (byte)~( i ) + " but got byte " + readbytes[i] ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); Log.Exception("Stack: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArguments, "InvalidArguments" ), new MFTestMethod( IOExceptionTests, "IOExceptionTests" ), new MFTestMethod( ValidCase, "ValidCase" ), }; } } } }
/* ==================================================================== 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 [email protected] or visit the website www.fyiReporting.com. */ using System; using System.IO; using System.Collections; using System.Text; namespace fyiReporting.RDL { /// <summary> /// A simple Lexer that is used by Parser. /// </summary> internal class Lexer { private TokenList tokens; private CharReader reader; /// <summary> /// Initializes a new instance of the Lexer class with the specified /// expression syntax to lex. /// </summary> /// <param name="expr">An expression to lex.</param> internal Lexer(string expr) : this(new StringReader(expr)) { // use this } /// <summary> /// Initializes a new instance of the Lexer class with the specified /// TextReader to lex. /// </summary> /// <param name="source">A TextReader to lex.</param> internal Lexer(TextReader source) { // token queue tokens = new TokenList(); // read the file contents reader = new CharReader(source); } /// <summary> /// Breaks the input stream onto the tokens list and returns it. /// </summary> /// <returns>The tokens list.</returns> internal TokenList Lex() { Token token = GetNextToken(); while(true) { if(token != null) tokens.Add(token); else { tokens.Add(new Token(null, reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.EOF)); return tokens; } token = GetNextToken(); } } private Token GetNextToken() { while(!reader.EndOfInput()) { char ch = reader.GetNext(); // skipping whitespaces if(Char.IsWhiteSpace(ch)) { continue; } switch(ch) { case '=': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.EQUAL); case '+': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.PLUS); case '-': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.MINUS); case '(': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.LPAREN); case ')': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.RPAREN); case ',': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.COMMA); case '^': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.EXP); case '%': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.MODULUS); case '!': if (reader.Peek() == '=') { reader.GetNext(); // go past the equal return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.NOTEQUAL); } else return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.NOT); case '&': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.PLUSSTRING); case '|': if (reader.Peek() == '|') { reader.GetNext(); // go past the '|' return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.OR); } break; case '>': if (reader.Peek() == '=') { reader.GetNext(); // go past the equal return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.GREATERTHANOREQUAL); } else return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.GREATERTHAN); case '/': if (reader.Peek() == '*') { // beginning of a comment of form /* a comment */ reader.GetNext(); // go past the '*' ReadComment(); continue; } else return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.FORWARDSLASH); case '<': if (reader.Peek() == '=') { reader.GetNext(); // go past the equal return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.LESSTHANOREQUAL); } else if (reader.Peek() == '>') { reader.GetNext(); // go past the > return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.NOTEQUAL); } else return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.LESSTHAN); case '*': return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.STAR); case '"': case '\'': return ReadQuoted(ch); default: break; } // end of swith if (Char.IsDigit(ch)) return ReadNumber(ch); else if (ch == '.') { char tc = reader.Peek(); if (Char.IsDigit(tc)) return ReadNumber(ch); return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.DOT); } else if (Char.IsLetter(ch) || ch == '_') return ReadIdentifier(ch); else return new Token(ch.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.OTHER); } return null; } // Reads a decimal number with optional exponentiation private Token ReadNumber(char ch) { int startLine = reader.Line; int startCol = reader.Column; bool bDecimal = ch == '.'? true: false; bool bDecimalType=false; // found d or D in number bool bFloat=false; // found e or E in number char cPeek; string number = ch.ToString(); while(!reader.EndOfInput() ) { cPeek = reader.Peek(); if (Char.IsWhiteSpace(cPeek)) break; if (Char.IsDigit(cPeek)) number += reader.GetNext(); else if ((cPeek == 'd' || cPeek == 'D') && !bFloat) { reader.GetNext(); // skip the 'd' bDecimalType = true; break; } else if ((cPeek == 'e' || cPeek == 'E') && !bFloat) { number += reader.GetNext(); // add the 'e' cPeek = reader.Peek(); if (cPeek == '-' || cPeek == '+') // +/- after e is optional assumes + number += reader.GetNext(); bFloat = true; if (Char.IsDigit(reader.Peek())) continue; throw new ParserException("Invalid number constant."); } else if (!bDecimal && !bFloat && cPeek == '.') // can't already be decimal or float { bDecimal = true; number += reader.GetNext(); } else break; // another character } if (number.CompareTo(".") == 0) throw new ParserException("'.' should be followed by a number"); TokenTypes t; if (bDecimalType) t = TokenTypes.NUMBER; else if (bFloat || bDecimal) t = TokenTypes.DOUBLE; else t = TokenTypes.INTEGER; return new Token(number, startLine, startCol, reader.Line, reader.Column, t); } // Reads an identifier: // Must consist of letters, digits, "_". "!", "." are allowed // but have special meaning that is disambiguated later private Token ReadIdentifier(char ch) { int startLine = reader.Line; int startCol = reader.Column; char cPeek; StringBuilder identifier = new StringBuilder(30); // initial capacity 30 characters identifier.Append(ch.ToString()); int state = 1; // state=1 means accept letter,digit,'.','!','_' // state=2 means accept whitespace ends with '.' or '!' // state=3 means accept letter to start new qualifier while (!reader.EndOfInput()) { cPeek = reader.Peek(); if (state == 1) { if (Char.IsLetterOrDigit(cPeek) || cPeek == '.' || cPeek == '!' || cPeek == '_') identifier.Append(reader.GetNext()); else if (Char.IsWhiteSpace(cPeek)) { reader.GetNext(); // skip space if (identifier[identifier.Length - 1] == '.' || identifier[identifier.Length - 1] == '!') state = 3; // need to have an identfier next else state = 2; // need to get '.' or '!' next } else break; } else if (state == 2) { // state must equal 2 if (cPeek == '.' || cPeek == '!') { state = 3; identifier.Append(reader.GetNext()); } else if (Char.IsWhiteSpace(cPeek)) reader.GetNext(); else break; } else { // state must equal 3 if (Char.IsLetter(cPeek) || cPeek == '_') { state = 1; identifier.Append(reader.GetNext()); } else if (Char.IsWhiteSpace(cPeek)) { reader.GetNext(); } else break; } } string key = identifier.ToString().ToLower(); if (key == "and" || key == "andalso") // technically 'and' and 'andalso' mean different things; but we treat the same return new Token(identifier.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.AND); else if (key == "or" || key == "orelse") // technically 'or' and 'orelse' mean different things; but we treat the same return new Token(identifier.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.OR); else if (key == "not") return new Token(identifier.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.NOT); else if (key == "mod") return new Token(identifier.ToString(), reader.Line, reader.Column, reader.Line, reader.Column, TokenTypes.MODULUS); // normal identifier return new Token(identifier.ToString(), startLine, startCol, reader.Line, reader.Column, TokenTypes.IDENTIFIER); } // Quoted string like " asdf " or ' asdf ' private Token ReadQuoted(char ch) { char qChar = ch; int startLine = reader.Line; int startCol = reader.Column; StringBuilder quoted = new StringBuilder(); while(!reader.EndOfInput()) { ch = reader.GetNext(); if (ch == '\\') { char pChar = reader.Peek(); if (pChar == qChar) ch = reader.GetNext(); // got one skip escape char else if (pChar == 'n') { ch = '\n'; reader.GetNext(); // skip the character } else if (pChar == 'r') { ch = '\r'; reader.GetNext(); // skip the character } } else if (ch == qChar) { if (reader.Peek() == ch) // did user double the quote? ch = reader.GetNext(); // yes, we just append one character else return new Token(quoted.ToString(), startLine, startCol, reader.Line, reader.Column, TokenTypes.QUOTE); } quoted.Append(ch); } throw new ParserException("Unterminated string!"); } // Comment string like /* this is a comment */ private void ReadComment() { char ch; while(!reader.EndOfInput()) { ch = reader.GetNext(); if (ch == '*' && reader.Peek() == '/') { reader.GetNext(); // skip past the '/' return; } } throw new ParserException("Unterminated comment!"); } // // Handles case of "<", "<=", and "<! ... xml string !> // private Token ReadXML(char ch) // { // int startLine = reader.Line; // int startCol = reader.Column; // // if (reader.EndOfInput()) // return new Token(ch.ToString(), startLine, startCol, startLine, startCol, TokenTypes.LESSTHAN); // ch = reader.GetNext(); // if (ch == '=') // return new Token("<=", startLine, startCol, reader.Line, reader.Column, TokenTypes.LESSTHANOREQUAL); // if (ch != '!') // If it's not '!' then it's not XML // { // reader.UnGet(); // put back the character // return new Token("<", startLine, startCol, reader.Line, reader.Column, TokenTypes.LESSTHAN); // } // // string xml = ""; // intialize our string // // while(!reader.EndOfInput()) // { // ch = reader.GetNext(); // // if(ch == '!') // check for end of XML denoted by "!>" // { // if (!reader.EndOfInput() && reader.Peek() == '>') // { // reader.GetNext(); // pull the '>' off the input // return new Token(xml, startLine, startCol, reader.Line, reader.Column, TokenTypes.XML); // } // } // // xml += ch.ToString(); // } // throw new ParserException("Unterminated XML clause!"); // } } }
using System; using System.Text; using Sandbox.ModAPI; using VRage.Game.Components; using VRage.ModAPI; using Sandbox.Common.ObjectBuilders; using VRage.ObjectBuilders; using Sandbox.Definitions; using VRage.Game; using Sandbox.Game.EntityComponents; using VRage.Game.Entity; using Sandbox.Game; using VRageMath; using SpaceEngineers.Game.ModAPI; using VRage.Game.ModAPI; using System.Collections.Generic; using Sandbox.Game.Entities; using Sandbox.ModAPI.Interfaces; using System.Linq; using Ingame = Sandbox.ModAPI.Ingame; namespace Cheetah.AI { public enum BotTypes { None, Invalid, Station, Fighter, Freighter, Carrier } static public class BotFabric { static public BotBase FabricateBot(IMyCubeGrid Grid, IMyRemoteControl RC) { try { BotTypes BotType = BotBase.ReadBotType(RC); BotBase Bot = null; switch (BotType) { case BotTypes.Fighter: Bot = new FighterBot(Grid); break; case BotTypes.Freighter: Bot = new FreighterBot(Grid); break; case BotTypes.Station: Bot = new StationBot(Grid); break; default: if (AISessionCore.AllowThrowingErrors) throw new Exception("Invalid bot type"); break; } return Bot; } catch (Exception Scrap) { Grid.LogError("BotFabric.FabricateBot", Scrap); return null; } } } abstract public class BotBase { public IMyCubeGrid Grid { get; protected set; } protected readonly IMyGridTerminalSystem Term; public Vector3D GridPosition { get { return Grid.GetPosition(); } } protected float GridRadius { get { return (float)Grid.WorldVolume.Radius; } } protected readonly TimeSpan CalmdownTime = (!AISessionCore.Debug ? TimeSpan.FromMinutes(15) : TimeSpan.FromMinutes(3)); protected bool initialized { get { try { return Grid != null; } catch (Exception Scrap) { LogError("initialized", Scrap); return false; } } } virtual public bool Initialized { get { return initialized; } } public MyEntityUpdateEnum Update { get; protected set; } public IMyRemoteControl RC { get; protected set; } IMyFaction OwnerFaction; protected string DroneNameProvider { get { return $"Drone_{RC.EntityId}"; } } public string DroneName { get { return RC.Name; } protected set { IMyEntity entity = RC as IMyEntity; entity.Name = value; MyAPIGateway.Entities.SetEntityName(entity, true); //DebugWrite("DroneName_Set", $"Drone EntityName set to {RC.Name}"); } } protected bool gridoperable { get { try { return !Grid.MarkedForClose && !Grid.Closed && Grid.InScene; } catch (Exception Scrap) { LogError("gridoperable", Scrap); return false; } } } protected bool BotOperable = false; protected bool Closed; virtual public bool Operable { get { try { return !Closed && Initialized && gridoperable && RC.IsFunctional && BotOperable; } catch (Exception Scrap) { LogError("Operable", Scrap); return false; } } } public List<IMyRadioAntenna> Antennae { get; protected set; } public delegate void OnDamageTaken(IMySlimBlock DamagedBlock, MyDamageInformation Damage); protected event OnDamageTaken OnDamaged; public delegate void hOnBlockPlaced(IMySlimBlock Block); protected event hOnBlockPlaced OnBlockPlaced; protected event Action Alert; public BotBase(IMyCubeGrid Grid) { if (Grid == null) return; this.Grid = Grid; Term = Grid.GetTerminalSystem(); Antennae = new List<IMyRadioAntenna>(); } static public BotTypes ReadBotType(IMyRemoteControl RC) { try { string _CustomData = RC.CustomData.Trim().Replace("\r\n", "\n"); List<string> CustomData = new List<string>(_CustomData.Split('\n')); if (_CustomData.IsNullEmptyOrWhiteSpace()) return BotTypes.None; if (CustomData.Count < 2) { if (AISessionCore.AllowThrowingErrors) throw new Exception("CustomData is invalid", new Exception("CustomData consists of less than two lines")); else return BotTypes.Invalid; } if (CustomData[0].Trim() != "[EEM_AI]") { if (AISessionCore.AllowThrowingErrors) throw new Exception("CustomData is invalid", new Exception($"AI tag invalid: '{CustomData[0]}'")); return BotTypes.Invalid; } string[] bottype = CustomData[1].Split(':'); if (bottype[0].Trim() != "Type") { if (AISessionCore.AllowThrowingErrors) throw new Exception("CustomData is invalid", new Exception($"Type tag invalid: '{bottype[0]}'")); return BotTypes.Invalid; } BotTypes BotType = BotTypes.Invalid; switch (bottype[1].Trim()) { case "Fighter": BotType = BotTypes.Fighter; break; case "Freighter": BotType = BotTypes.Freighter; break; case "Carrier": BotType = BotTypes.Carrier; break; case "Station": BotType = BotTypes.Station; break; } return BotType; } catch (Exception Scrap) { RC.CubeGrid.LogError("[STATIC]BotBase.ReadBotType", Scrap); return BotTypes.Invalid; } } virtual protected void DebugWrite(string Source, string Message, string DebugPrefix = "BotBase.") { Grid.DebugWrite(DebugPrefix + Source, Message); } virtual public bool Init(IMyRemoteControl RC = null) { this.RC = RC ?? Term.GetBlocksOfType<IMyRemoteControl>(collect: x => x.IsFunctional).FirstOrDefault(); if (RC == null) return false; DroneName = DroneNameProvider; Antennae = Term.GetBlocksOfType<IMyRadioAntenna>(collect: x => x.IsFunctional); bool HasSetup = ParseSetup(); if (!HasSetup) return false; AISessionCore.AddDamageHandler(Grid, (Block, Damage) => OnDamaged(Block, Damage)); Grid.OnBlockAdded += (Block) => OnBlockPlaced(Block); OwnerFaction = Grid.GetOwnerFaction(RecalculateOwners: true); BotOperable = true; return true; } virtual public void RecompilePBs() { foreach (IMyProgrammableBlock PB in Term.GetBlocksOfType<IMyProgrammableBlock>()) { PB.Recompile(); } } virtual protected void ReactOnDamage(IMySlimBlock Block, MyDamageInformation Damage, TimeSpan TruceDelay, out IMyPlayer Damager) { Damager = null; try { if (Damage.IsMeteor()) { Grid.DebugWrite("ReactOnDamage", "Grid was damaged by meteor. Ignoring."); return; } if (Damage.IsThruster()) { if (Block != null && !Block.IsDestroyed) { Grid.DebugWrite("ReactOnDamage", "Grid was slighly damaged by thruster. Ignoring."); return; } } try { if (Damage.IsDoneByPlayer(out Damager) && Damager != null) { try { Grid.DebugWrite("ReactOnDamage", $"Grid is damaged by player {Damager.DisplayName}. Trying to activate alert."); RegisterHostileAction(Damager, TruceDelay); } catch (Exception Scrap) { Grid.LogError("ReactOnDamage.GetDamagerFaction", Scrap); } } else Grid.DebugWrite("ReactOnDamage", "Grid is damaged, but damage source is not recognized as player."); } catch (Exception Scrap) { Grid.LogError("ReactOnDamage.IsDamageDoneByPlayer", Scrap); } } catch (Exception Scrap) { Grid.LogError("ReactOnDamage", Scrap); } } virtual protected void BlockPlacedHandler(IMySlimBlock Block) { if (Block == null) return; try { IMyPlayer Builder = null; IMyFaction Faction = null; if (Block.IsPlayerBlock(out Builder)) { Faction = Builder.GetFaction(); if (Faction != null) { RegisterHostileAction(Faction, CalmdownTime); } } } catch (Exception Scrap) { Grid.LogError("BlokPlaedHandler", Scrap); } } virtual protected void RegisterHostileAction(IMyPlayer Player, TimeSpan TruceDelay) { try { #region Sanity checks if (Player == null) { Grid.DebugWrite("RegisterHostileAction", "Error: Damager is null."); return; }; if (OwnerFaction == null) { OwnerFaction = Grid.GetOwnerFaction(); } if (OwnerFaction == null || !OwnerFaction.IsNPC()) { Grid.DebugWrite("RegisterHostileAction", $"Error: {(OwnerFaction == null ? "can't find own faction" : "own faction isn't recognized as NPC.")}"); return; } #endregion IMyFaction HostileFaction = Player.GetFaction(); if (HostileFaction == null) { Grid.DebugWrite("RegisterHostileAction", "Error: can't find damager's faction"); return; } else if (HostileFaction == OwnerFaction) { OwnerFaction.Kick(Player); return; } AISessionCore.DeclareWar(OwnerFaction, HostileFaction, TruceDelay); if (OwnerFaction.IsLawful()) { AISessionCore.DeclareWar(Diplomacy.Police, HostileFaction, TruceDelay); AISessionCore.DeclareWar(Diplomacy.Army, HostileFaction, TruceDelay); } } catch (Exception Scrap) { LogError("RegisterHostileAction", Scrap); } } virtual protected void RegisterHostileAction(IMyFaction HostileFaction, TimeSpan TruceDelay) { try { if (HostileFaction == null) { Grid.DebugWrite("RegisterHostileAction", "Error: can't find damager's faction"); return; } AISessionCore.DeclareWar(OwnerFaction, HostileFaction, TruceDelay); if (OwnerFaction.IsLawful()) { AISessionCore.DeclareWar(Diplomacy.Police, HostileFaction, TruceDelay); AISessionCore.DeclareWar(Diplomacy.Army, HostileFaction, TruceDelay); } } catch (Exception Scrap) { LogError("RegisterHostileAction", Scrap); } } protected List<Ingame.MyDetectedEntityInfo> LookAround(float Radius, Func<Ingame.MyDetectedEntityInfo, bool> Filter = null) { List<Ingame.MyDetectedEntityInfo> RadarData = new List<Ingame.MyDetectedEntityInfo>(); BoundingSphereD LookaroundSphere = new BoundingSphereD(GridPosition, Radius); List<IMyEntity> EntitiesAround = MyAPIGateway.Entities.GetTopMostEntitiesInSphere(ref LookaroundSphere); EntitiesAround.RemoveAll(x => x == Grid || GridPosition.DistanceTo(x.GetPosition()) < GridRadius * 1.5); long OwnerID; if (OwnerFaction != null) { OwnerID = OwnerFaction.FounderId; Grid.DebugWrite("LookAround", "Found owner via faction owner"); } else { OwnerID = RC.OwnerId; Grid.DebugWrite("LookAround", "OWNER FACTION NOT FOUND, found owner via RC owner"); } foreach (IMyEntity DetectedEntity in EntitiesAround) { Ingame.MyDetectedEntityInfo RadarDetectedEntity = MyDetectedEntityInfoHelper.Create(DetectedEntity as MyEntity, OwnerID); if (Filter == null ? true : (Filter(RadarDetectedEntity))) RadarData.Add(RadarDetectedEntity); } //DebugWrite("LookAround", $"Radar entities detected: {String.Join(" | ", RadarData.Select(x => $"{x.Name}"))}"); return RadarData; } protected List<Ingame.MyDetectedEntityInfo> LookForEnemies(float Radius, bool ConsiderNeutralsAsHostiles = false) { if (!ConsiderNeutralsAsHostiles) return LookAround(Radius, x => x.Relationship == MyRelationsBetweenPlayerAndBlock.Enemies); else return LookAround(Radius, x => x.Relationship == MyRelationsBetweenPlayerAndBlock.Enemies || x.Relationship == MyRelationsBetweenPlayerAndBlock.Neutral); } virtual protected List<IMyTerminalBlock> GetHackedBlocks() { List<IMyTerminalBlock> TerminalBlocks = new List<IMyTerminalBlock>(); List<IMyTerminalBlock> HackedBlocks = new List<IMyTerminalBlock>(); Term.GetBlocks(TerminalBlocks); foreach (IMyTerminalBlock Block in TerminalBlocks) if (Block.IsBeingHacked) HackedBlocks.Add(Block); return HackedBlocks; } virtual protected List<IMySlimBlock> GetDamagedBlocks() { List<IMySlimBlock> Blocks = new List<IMySlimBlock>(); Grid.GetBlocks(Blocks, x => x.CurrentDamage > 10); return Blocks; } protected bool HasModdedThrusters => SpeedmoddedThrusters.Count > 0; protected List<IMyThrust> SpeedmoddedThrusters = new List<IMyThrust>(); protected void ApplyThrustMultiplier(float ThrustMultiplier) { DemultiplyThrusters(); foreach (IMyThrust Thruster in Term.GetBlocksOfType<IMyThrust>(collect: x => x.IsOwnedByNPC(AllowNobody: false, CheckBuilder: true))) { Thruster.ThrustMultiplier = ThrustMultiplier; Thruster.OwnershipChanged += Thruster_OnOwnerChanged; SpeedmoddedThrusters.Add(Thruster); } } protected void DemultiplyThrusters() { if (!HasModdedThrusters) return; foreach (IMyThrust Thruster in SpeedmoddedThrusters) { if (Thruster.ThrustMultiplier != 1) Thruster.ThrustMultiplier = 1; } SpeedmoddedThrusters.Clear(); } private void Thruster_OnOwnerChanged(IMyTerminalBlock thruster) { try { IMyThrust Thruster = thruster as IMyThrust; if (Thruster == null) return; if (!Thruster.IsOwnedByNPC() && Thruster.ThrustMultiplier != 1) Thruster.ThrustMultiplier = 1; } catch (Exception Scrap) { Grid.DebugWrite("Thruster_OnOwnerChanged", $"{thruster.CustomName} OnOwnerChanged failed: {Scrap.Message}"); } } abstract protected bool ParseSetup(); abstract public void Main(); virtual public void Shutdown() { Closed = true; if (HasModdedThrusters) DemultiplyThrusters(); AISessionCore.RemoveDamageHandler(Grid); } public void LogError(string Source, Exception Scrap, string DebugPrefix = "BotBase.") { Grid.LogError(DebugPrefix + Source, Scrap); } } /*public sealed class InvalidBot : BotBase { static public readonly BotTypes BotType = BotTypes.None; public override bool Operable { get { return false; } } public InvalidBot(IMyCubeGrid Grid = null) : base(Grid) { } public override bool Init(IMyRemoteControl RC = null) { return false; } public override void Main() { // Empty } protected override bool ParseSetup() { return false; } }*/ }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; namespace UMA { /// <summary> /// Utility class for generating texture atlases /// </summary> [Serializable] public class UMAGeneratorCoroutine : WorkerCoroutine { TextureProcessBaseCoroutine textureProcessCoroutine; MaxRectsBinPack packTexture; UMAGeneratorBase umaGenerator; UMAData umaData; Texture[] backUpTexture; bool updateMaterialList; MaterialDefinitionComparer comparer = new MaterialDefinitionComparer(); List<UMAData.GeneratedMaterial> generatedMaterials; List<UMAData.GeneratedMaterial> atlassedMaterials = new List<UMAData.GeneratedMaterial>(20); Dictionary<List<OverlayData>, UMAData.GeneratedMaterial> generatedMaterialLookup; public void Prepare(UMAGeneratorBase _umaGenerator, UMAData _umaData, TextureProcessBaseCoroutine textureProcessCoroutine, bool updateMaterialList) { umaGenerator = _umaGenerator; umaData = _umaData; this.textureProcessCoroutine = textureProcessCoroutine; this.updateMaterialList = updateMaterialList; } private UMAData.GeneratedMaterial FindOrCreateGeneratedMaterial(UMAMaterial umaMaterial) { if (umaMaterial.materialType != UMAMaterial.MaterialType.Atlas) { var res = new UMAData.GeneratedMaterial(); res.umaMaterial = umaMaterial; res.material = UnityEngine.Object.Instantiate(umaMaterial.material) as Material; res.material.name = umaMaterial.material.name; generatedMaterials.Add(res); return res; } else { foreach (var atlassedMaterial in atlassedMaterials) { if (atlassedMaterial.umaMaterial == umaMaterial) { return atlassedMaterial; } else { if (atlassedMaterial.umaMaterial.Equals(umaMaterial)) { return atlassedMaterial; } } } var res = new UMAData.GeneratedMaterial(); res.umaMaterial = umaMaterial; res.material = UnityEngine.Object.Instantiate(umaMaterial.material) as Material; res.material.name = umaMaterial.material.name; atlassedMaterials.Add(res); generatedMaterials.Add(res); return res; } } protected override void Start() { if (generatedMaterialLookup == null) { generatedMaterialLookup = new Dictionary<List<OverlayData>, UMAData.GeneratedMaterial>(20); } else { generatedMaterialLookup.Clear(); } backUpTexture = umaData.backUpTextures(); umaData.CleanTextures(); generatedMaterials = new List<UMAData.GeneratedMaterial>(20); atlassedMaterials.Clear(); SlotData[] slots = umaData.umaRecipe.slotDataList; for (int i = 0; i < slots.Length; i++) { var slot = slots[i]; if (slot == null) continue; if (slot.asset.material != null && slot.GetOverlay(0) != null) { var overlayList = slot.GetOverlayList(); UMAData.GeneratedMaterial generatedMaterial; if (!generatedMaterialLookup.TryGetValue(overlayList, out generatedMaterial)) { generatedMaterial = FindOrCreateGeneratedMaterial(slots[i].asset.material); generatedMaterialLookup.Add(overlayList, generatedMaterial); } var tempMaterialDefinition = new UMAData.MaterialFragment(); tempMaterialDefinition.baseTexture = slots[i].GetOverlay(0).asset.textureList; tempMaterialDefinition.size = tempMaterialDefinition.baseTexture[0].width * tempMaterialDefinition.baseTexture[0].height; tempMaterialDefinition.baseColor = slots[i].GetOverlay(0).colorData.color; tempMaterialDefinition.umaMaterial = slots[i].asset.material; int overlays = 0; for (int overlayCounter = 0; overlayCounter < slots[i].OverlayCount; overlayCounter++) { var overlay = slots[i].GetOverlay(overlayCounter); if (overlay != null) { overlays++; } } tempMaterialDefinition.overlays = new UMAData.textureData[overlays - 1]; tempMaterialDefinition.overlayColors = new Color32[overlays - 1]; tempMaterialDefinition.rects = new Rect[overlays - 1]; tempMaterialDefinition.overlayData = new OverlayData[overlays]; tempMaterialDefinition.channelMask = new Color[overlays][]; tempMaterialDefinition.channelAdditiveMask = new Color[overlays][]; tempMaterialDefinition.overlayData[0] = slots[i].GetOverlay(0); tempMaterialDefinition.channelMask[0] = slots[i].GetOverlay(0).colorData.channelMask; tempMaterialDefinition.channelAdditiveMask[0] = slots[i].GetOverlay(0).colorData.channelAdditiveMask; tempMaterialDefinition.slotData = slots[i]; int overlayID = 0; for (int overlayCounter = 0; overlayCounter < slots[i].OverlayCount - 1; overlayCounter++) { var overlay = slots[i].GetOverlay(overlayCounter + 1); if (overlay == null) continue; tempMaterialDefinition.overlays[overlayID] = new UMAData.textureData(); tempMaterialDefinition.rects[overlayID] = overlay.rect; tempMaterialDefinition.overlays[overlayID].textureList = overlay.asset.textureList; tempMaterialDefinition.overlayColors[overlayID] = overlay.colorData.color; tempMaterialDefinition.channelMask[overlayID + 1] = overlay.colorData.channelMask; tempMaterialDefinition.channelAdditiveMask[overlayID + 1] = overlay.colorData.channelAdditiveMask; tempMaterialDefinition.overlayData[overlayID + 1] = overlay; overlayID++; } tempMaterialDefinition.overlayList = slots[i].GetOverlayList(); tempMaterialDefinition.isRectShared = false; for (int j = 0; j < generatedMaterial.materialFragments.Count; j++) { if (generatedMaterial.materialFragments[j].overlayList == tempMaterialDefinition.overlayList) { tempMaterialDefinition.isRectShared = true; tempMaterialDefinition.rectFragment = generatedMaterial.materialFragments[j]; break; } } generatedMaterial.materialFragments.Add(tempMaterialDefinition); } } packTexture = new MaxRectsBinPack(umaGenerator.atlasResolution, umaGenerator.atlasResolution, false); } public class MaterialDefinitionComparer : IComparer<UMAData.MaterialFragment> { public int Compare(UMAData.MaterialFragment x, UMAData.MaterialFragment y) { return y.size - x.size; } } protected override IEnumerator workerMethod() { umaData.generatedMaterials = new UMAData.GeneratedMaterials(); umaData.generatedMaterials.materials = generatedMaterials; GenerateAtlasData(); OptimizeAtlas(); textureProcessCoroutine.Prepare(umaData, umaGenerator); yield return textureProcessCoroutine; CleanBackUpTextures(); UpdateUV(); if (updateMaterialList) { var mats = umaData.myRenderer.sharedMaterials; var atlasses = umaData.generatedMaterials.materials; for (int i = 0; i < atlasses.Count; i++) { UnityEngine.Object.Destroy(mats[i]); mats[i] = atlasses[i].material; } umaData.myRenderer.sharedMaterials = new List<Material>(mats).ToArray(); } } protected override void Stop() { } private void CleanBackUpTextures() { for (int textureIndex = 0; textureIndex < backUpTexture.Length; textureIndex++) { if (backUpTexture[textureIndex] != null) { Texture tempTexture = backUpTexture[textureIndex]; if (tempTexture is RenderTexture) { RenderTexture tempRenderTexture = tempTexture as RenderTexture; tempRenderTexture.Release(); UnityEngine.Object.Destroy(tempRenderTexture); tempRenderTexture = null; } else { UnityEngine.Object.Destroy(tempTexture); } backUpTexture[textureIndex] = null; } } } private void GenerateAtlasData() { for (int i = 0; i < atlassedMaterials.Count; i++) { var generatedMaterial = atlassedMaterials[i]; generatedMaterial.materialFragments.Sort(comparer); generatedMaterial.resolutionScale = 1f; generatedMaterial.cropResolution = new Vector2(umaGenerator.atlasResolution, umaGenerator.atlasResolution); while (!CalculateRects(generatedMaterial)) { generatedMaterial.resolutionScale = generatedMaterial.resolutionScale * 0.5f; } UpdateSharedRect(generatedMaterial); } } private void UpdateSharedRect(UMAData.GeneratedMaterial generatedMaterial) { for (int i = 0; i < generatedMaterial.materialFragments.Count; i++) { var fragment = generatedMaterial.materialFragments[i]; if (fragment.isRectShared) { fragment.atlasRegion = fragment.rectFragment.atlasRegion; } } } private bool CalculateRects(UMAData.GeneratedMaterial material) { Rect nullRect = new Rect(0, 0, 0, 0); packTexture.Init(umaGenerator.atlasResolution, umaGenerator.atlasResolution, false); for (int atlasElementIndex = 0; atlasElementIndex < material.materialFragments.Count; atlasElementIndex++) { var tempMaterialDef = material.materialFragments[atlasElementIndex]; if (tempMaterialDef.isRectShared) continue; tempMaterialDef.atlasRegion = packTexture.Insert(Mathf.FloorToInt(tempMaterialDef.baseTexture[0].width * material.resolutionScale * tempMaterialDef.slotData.overlayScale), Mathf.FloorToInt(tempMaterialDef.baseTexture[0].height * material.resolutionScale * tempMaterialDef.slotData.overlayScale), MaxRectsBinPack.FreeRectChoiceHeuristic.RectBestLongSideFit); if (tempMaterialDef.atlasRegion == nullRect) { if (umaGenerator.fitAtlas) { Debug.LogWarning("Atlas resolution is too small, Textures will be reduced.", umaData.gameObject); return false; } else { Debug.LogError("Atlas resolution is too small, not all textures will fit.", umaData.gameObject); } } } return true; } private void OptimizeAtlas() { for (int atlasIndex = 0; atlasIndex < atlassedMaterials.Count; atlasIndex++) { var material = atlassedMaterials[atlasIndex]; Vector2 usedArea = new Vector2(0, 0); for (int atlasElementIndex = 0; atlasElementIndex < material.materialFragments.Count; atlasElementIndex++) { if (material.materialFragments[atlasElementIndex].atlasRegion.xMax > usedArea.x) { usedArea.x = material.materialFragments[atlasElementIndex].atlasRegion.xMax; } if (material.materialFragments[atlasElementIndex].atlasRegion.yMax > usedArea.y) { usedArea.y = material.materialFragments[atlasElementIndex].atlasRegion.yMax; } } Vector2 tempResolution = new Vector2(umaGenerator.atlasResolution, umaGenerator.atlasResolution); bool done = false; while (!done) { if (tempResolution.x * 0.5f >= usedArea.x) { tempResolution = new Vector2(tempResolution.x * 0.5f, tempResolution.y); } else { done = true; } } done = false; while (!done) { if (tempResolution.y * 0.5f >= usedArea.y) { tempResolution = new Vector2(tempResolution.x, tempResolution.y * 0.5f); } else { done = true; } } material.cropResolution = tempResolution; } } private void UpdateUV() { UMAData.GeneratedMaterials umaAtlasList = umaData.generatedMaterials; for (int atlasIndex = 0; atlasIndex < umaAtlasList.materials.Count; atlasIndex++) { Vector2 finalAtlasAspect = new Vector2(umaGenerator.atlasResolution / umaAtlasList.materials[atlasIndex].cropResolution.x, umaGenerator.atlasResolution / umaAtlasList.materials[atlasIndex].cropResolution.y); for (int atlasElementIndex = 0; atlasElementIndex < umaAtlasList.materials[atlasIndex].materialFragments.Count; atlasElementIndex++) { Rect tempRect = umaAtlasList.materials[atlasIndex].materialFragments[atlasElementIndex].atlasRegion; tempRect.xMin = tempRect.xMin * finalAtlasAspect.x; tempRect.xMax = tempRect.xMax * finalAtlasAspect.x; tempRect.yMin = tempRect.yMin * finalAtlasAspect.y; tempRect.yMax = tempRect.yMax * finalAtlasAspect.y; umaAtlasList.materials[atlasIndex].materialFragments[atlasElementIndex].atlasRegion = tempRect; } } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // 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. // using System; using System.Diagnostics; using System.Runtime.CompilerServices; namespace NLog.Fluent { /// <summary> /// A fluent class to build log events for NLog. /// </summary> public class LogBuilder { private readonly LogEventInfo _logEvent; private readonly Logger _logger; /// <summary> /// Initializes a new instance of the <see cref="LogBuilder"/> class. /// </summary> /// <param name="logger">The <see cref="Logger"/> to send the log event.</param> public LogBuilder(Logger logger) : this(logger, LogLevel.Debug) { } /// <summary> /// Initializes a new instance of the <see cref="LogBuilder"/> class. /// </summary> /// <param name="logger">The <see cref="Logger"/> to send the log event.</param> /// <param name="logLevel">The <see cref="LogLevel"/> for the log event.</param> public LogBuilder(Logger logger, LogLevel logLevel) { if (logger == null) throw new ArgumentNullException("logger"); if (logLevel == null) throw new ArgumentNullException("logLevel"); _logger = logger; _logEvent = new LogEventInfo { Level = logLevel, LoggerName = logger.Name, TimeStamp = DateTime.Now }; } /// <summary> /// Gets the <see cref="LogEventInfo"/> created by the builder. /// </summary> public LogEventInfo LogEventInfo { get { return _logEvent; } } /// <summary> /// Sets the <paramref name="exception"/> information of the logging event. /// </summary> /// <param name="exception">The exception information of the logging event.</param> /// <returns></returns> public LogBuilder Exception(Exception exception) { _logEvent.Exception = exception; return this; } /// <summary> /// Sets the level of the logging event. /// </summary> /// <param name="logLevel">The level of the logging event.</param> /// <returns></returns> public LogBuilder Level(LogLevel logLevel) { if (logLevel == null) throw new ArgumentNullException("logLevel"); _logEvent.Level = logLevel; return this; } /// <summary> /// Sets the logger name of the logging event. /// </summary> /// <param name="loggerName">The logger name of the logging event.</param> /// <returns></returns> public LogBuilder LoggerName(string loggerName) { _logEvent.LoggerName = loggerName; return this; } /// <summary> /// Sets the log message on the logging event. /// </summary> /// <param name="message">The log message for the logging event.</param> /// <returns></returns> public LogBuilder Message(string message) { _logEvent.Message = message; return this; } /// <summary> /// Sets the log message and parameters for formating on the logging event. /// </summary> /// <param name="format">A composite format string.</param> /// <param name="arg0">The object to format.</param> /// <returns></returns> public LogBuilder Message(string format, object arg0) { _logEvent.Message = format; _logEvent.Parameters = new[] { arg0 }; return this; } /// <summary> /// Sets the log message and parameters for formating on the logging event. /// </summary> /// <param name="format">A composite format string.</param> /// <param name="arg0">The first object to format.</param> /// <param name="arg1">The second object to format.</param> /// <returns></returns> public LogBuilder Message(string format, object arg0, object arg1) { _logEvent.Message = format; _logEvent.Parameters = new[] { arg0, arg1 }; return this; } /// <summary> /// Sets the log message and parameters for formating on the logging event. /// </summary> /// <param name="format">A composite format string.</param> /// <param name="arg0">The first object to format.</param> /// <param name="arg1">The second object to format.</param> /// <param name="arg2">The third object to format.</param> /// <returns></returns> public LogBuilder Message(string format, object arg0, object arg1, object arg2) { _logEvent.Message = format; _logEvent.Parameters = new[] { arg0, arg1, arg2 }; return this; } /// <summary> /// Sets the log message and parameters for formating on the logging event. /// </summary> /// <param name="format">A composite format string.</param> /// <param name="arg0">The first object to format.</param> /// <param name="arg1">The second object to format.</param> /// <param name="arg2">The third object to format.</param> /// <param name="arg3">The fourth object to format.</param> /// <returns></returns> public LogBuilder Message(string format, object arg0, object arg1, object arg2, object arg3) { _logEvent.Message = format; _logEvent.Parameters = new[] { arg0, arg1, arg2, arg3 }; return this; } /// <summary> /// Sets the log message and parameters for formating on the logging event. /// </summary> /// <param name="format">A composite format string.</param> /// <param name="args">An object array that contains zero or more objects to format.</param> /// <returns></returns> public LogBuilder Message(string format, params object[] args) { _logEvent.Message = format; _logEvent.Parameters = args; return this; } /// <summary> /// Sets the log message and parameters for formating on the logging event. /// </summary> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <param name="format">A composite format string.</param> /// <param name="args">An object array that contains zero or more objects to format.</param> /// <returns></returns> public LogBuilder Message(IFormatProvider provider, string format, params object[] args) { _logEvent.FormatProvider = provider; _logEvent.Message = format; _logEvent.Parameters = args; return this; } /// <summary> /// Sets a per-event context property on the logging event. /// </summary> /// <param name="name">The name of the context property.</param> /// <param name="value">The value of the context property.</param> /// <returns></returns> public LogBuilder Property(object name, object value) { if (name == null) throw new ArgumentNullException("name"); _logEvent.Properties[name] = value; return this; } /// <summary> /// Sets the timestamp of the logging event. /// </summary> /// <param name="timeStamp">The timestamp of the logging event.</param> /// <returns></returns> public LogBuilder TimeStamp(DateTime timeStamp) { _logEvent.TimeStamp = timeStamp; return this; } /// <summary> /// Sets the stack trace for the event info. /// </summary> /// <param name="stackTrace">The stack trace.</param> /// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param> /// <returns></returns> public LogBuilder StackTrace(StackTrace stackTrace, int userStackFrame) { _logEvent.SetStackTrace(stackTrace, userStackFrame); return this; } #if NET4_5 /// <summary> /// Writes the log event to the underlying logger. /// </summary> /// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param> /// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param> public void Write( [CallerMemberName]string callerMemberName = null, [CallerFilePath]string callerFilePath = null, [CallerLineNumber]int callerLineNumber = 0) { if (callerMemberName != null) Property("CallerMemberName", callerMemberName); if (callerFilePath != null) Property("CallerFilePath", callerFilePath); if (callerLineNumber != 0) Property("CallerLineNumber", callerLineNumber); _logger.Log(_logEvent); } #else /// <summary> /// Writes the log event to the underlying logger. /// </summary> public void Write() { _logger.Log(_logEvent); } #endif #if NET4_5 /// <summary> /// Writes the log event to the underlying logger if the condition delegate is true. /// </summary> /// <param name="condition">If condition is true, write log event; otherwise ignore event.</param> /// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param> /// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param> public void WriteIf( Func<bool> condition, [CallerMemberName]string callerMemberName = null, [CallerFilePath]string callerFilePath = null, [CallerLineNumber]int callerLineNumber = 0) { if (condition == null || !condition()) return; if (callerMemberName != null) Property("CallerMemberName", callerMemberName); if (callerFilePath != null) Property("CallerFilePath", callerFilePath); if (callerLineNumber != 0) Property("CallerLineNumber", callerLineNumber); _logger.Log(_logEvent); } #else /// <summary> /// Writes the log event to the underlying logger. /// </summary> /// <param name="condition">If condition is true, write log event; otherwise ignore event.</param> public void WriteIf(Func<bool> condition) { if (condition == null || !condition()) return; _logger.Log(_logEvent); } #endif #if NET4_5 /// <summary> /// Writes the log event to the underlying logger if the condition is true. /// </summary> /// <param name="condition">If condition is true, write log event; otherwise ignore event.</param> /// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param> /// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param> public void WriteIf( bool condition, [CallerMemberName]string callerMemberName = null, [CallerFilePath]string callerFilePath = null, [CallerLineNumber]int callerLineNumber = 0) { if (!condition) return; if (callerMemberName != null) Property("CallerMemberName", callerMemberName); if (callerFilePath != null) Property("CallerFilePath", callerFilePath); if (callerLineNumber != 0) Property("CallerLineNumber", callerLineNumber); _logger.Log(_logEvent); } #else /// <summary> /// Writes the log event to the underlying logger. /// </summary> /// <param name="condition">If condition is true, write log event; otherwise ignore event.</param> public void WriteIf(bool condition) { if (!condition) return; _logger.Log(_logEvent); } #endif } }
using NQuery.Symbols; using NQuery.Syntax; using NQuery.Text; namespace NQuery.Authoring.Classifications { internal sealed class SemanticClassificationWorker { private readonly List<SemanticClassificationSpan> _result; private readonly SemanticModel _semanticModel; private readonly TextSpan _span; public SemanticClassificationWorker(List<SemanticClassificationSpan> result, SemanticModel semanticModel, TextSpan span) { _result = result; _semanticModel = semanticModel; _span = span; } private void AddClassification(TextSpan textSpan, Symbol symbol) { if (textSpan.Length == 0) return; var classification = GetClassification(symbol); if (classification is null) return; _result.Add(new SemanticClassificationSpan(textSpan, classification.Value)); } private void AddClassification(SyntaxNodeOrToken nodeOrToken, Symbol symbol) { AddClassification(nodeOrToken.Span, symbol); } private static SemanticClassification? GetClassification(Symbol symbol) { switch (symbol.Kind) { case SymbolKind.ErrorTable: return null; case SymbolKind.SchemaTable: return SemanticClassification.SchemaTable; case SymbolKind.Column: return SemanticClassification.Column; case SymbolKind.DerivedTable: return SemanticClassification.DerivedTable; case SymbolKind.CommonTableExpression: return SemanticClassification.CommonTableExpression; case SymbolKind.TableInstance: return GetClassification(((TableInstanceSymbol)symbol).Table); case SymbolKind.TableColumnInstance: case SymbolKind.QueryColumnInstance: return SemanticClassification.Column; case SymbolKind.Function: return SemanticClassification.Function; case SymbolKind.Aggregate: return SemanticClassification.Aggregate; case SymbolKind.Variable: return SemanticClassification.Variable; case SymbolKind.Property: return SemanticClassification.Property; case SymbolKind.Method: return SemanticClassification.Method; default: throw new ArgumentOutOfRangeException(nameof(symbol)); } } public void ClassifyNode(SyntaxNode node) { if (!node.FullSpan.OverlapsWith(_span)) return; switch (node.Kind) { case SyntaxKind.CommonTableExpression: ClassifyCommonTableExpression((CommonTableExpressionSyntax)node); break; case SyntaxKind.CommonTableExpressionColumnName: ClassifyCommonTableExpressionColumnName((CommonTableExpressionColumnNameSyntax)node); break; case SyntaxKind.NameExpression: ClassifyNameExpression((NameExpressionSyntax)node); break; case SyntaxKind.VariableExpression: ClassifyVariableExpression((VariableExpressionSyntax)node); break; case SyntaxKind.FunctionInvocationExpression: ClassifyFunctionInvocationExpression((FunctionInvocationExpressionSyntax)node); break; case SyntaxKind.CountAllExpression: ClassifyCountAllExpression((CountAllExpressionSyntax)node); break; case SyntaxKind.PropertyAccessExpression: ClassifyPropertyAccess((PropertyAccessExpressionSyntax)node); break; case SyntaxKind.MethodInvocationExpression: ClassifyMethodInvocationExpression((MethodInvocationExpressionSyntax)node); break; case SyntaxKind.WildcardSelectColumn: ClassifyWildcardSelectColumn((WildcardSelectColumnSyntax)node); break; case SyntaxKind.ExpressionSelectColumn: ClassifyExpressionSelectColumn((ExpressionSelectColumnSyntax)node); break; case SyntaxKind.NamedTableReference: ClassifyNamedTableReference((NamedTableReferenceSyntax)node); break; case SyntaxKind.DerivedTableReference: ClassifyDerivedTableReference((DerivedTableReferenceSyntax)node); break; default: VisitChildren(node); break; } } private void VisitChildren(SyntaxNode node) { var nodes = node.ChildNodes() .SkipWhile(n => !n.FullSpan.IntersectsWith(_span)) .TakeWhile(n => n.FullSpan.IntersectsWith(_span)); foreach (var childNode in nodes) ClassifyNode(childNode); } private void ClassifyCommonTableExpression(CommonTableExpressionSyntax node) { var symbol = _semanticModel.GetDeclaredSymbol(node); if (symbol is not null) AddClassification(node.Name, symbol); VisitChildren(node); } private void ClassifyCommonTableExpressionColumnName(CommonTableExpressionColumnNameSyntax node) { var symbol = _semanticModel.GetDeclaredSymbol(node); if (symbol is null) return; AddClassification(node, symbol); } private void ClassifyExpression(ExpressionSyntax node, SyntaxNodeOrToken context) { var symbol = _semanticModel.GetSymbol(node); if (symbol is null) return; AddClassification(context, symbol); } private void ClassifyNameExpression(NameExpressionSyntax node) { ClassifyExpression(node, node.Name); } private void ClassifyVariableExpression(VariableExpressionSyntax node) { ClassifyExpression(node, node); } private void ClassifyFunctionInvocationExpression(FunctionInvocationExpressionSyntax node) { ClassifyExpression(node, node.Name); ClassifyNode(node.ArgumentList); } private void ClassifyCountAllExpression(CountAllExpressionSyntax node) { ClassifyExpression(node, node.Name); } private void ClassifyPropertyAccess(PropertyAccessExpressionSyntax node) { ClassifyNode(node.Target); ClassifyExpression(node, node.Name); } private void ClassifyMethodInvocationExpression(MethodInvocationExpressionSyntax node) { ClassifyNode(node.Target); ClassifyExpression(node, node.Name); ClassifyNode(node.ArgumentList); } private void ClassifyWildcardSelectColumn(WildcardSelectColumnSyntax node) { var tableInstanceSymbol = _semanticModel.GetTableInstance(node); if (tableInstanceSymbol is null) return; AddClassification(node.TableName, tableInstanceSymbol); } private void ClassifyExpressionSelectColumn(ExpressionSelectColumnSyntax node) { ClassifyNode(node.Expression); if (node.Alias is null) return; var queryColumnInstanceSymbol = _semanticModel.GetDeclaredSymbol(node); AddClassification(node.Alias.Identifier, queryColumnInstanceSymbol); } private void ClassifyNamedTableReference(NamedTableReferenceSyntax node) { var tableInstanceSymbol = _semanticModel.GetDeclaredSymbol(node); if (tableInstanceSymbol is null) return; AddClassification(node.TableName, tableInstanceSymbol.Table); if (node.Alias is not null) AddClassification(node.Alias.Identifier, tableInstanceSymbol); } private void ClassifyDerivedTableReference(DerivedTableReferenceSyntax node) { ClassifyNode(node.Query); var tableInstanceSymbol = _semanticModel.GetDeclaredSymbol(node); if (tableInstanceSymbol is not null) AddClassification(node.Name, tableInstanceSymbol); } } }
using J2N.Numerics; using Lucene.Net.Support; using System; using System.Diagnostics; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using DocIdSet = Lucene.Net.Search.DocIdSet; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; /// <summary> /// An "open" BitSet implementation that allows direct access to the array of words /// storing the bits. /// <para/> /// NOTE: This can be used in .NET any place where a <c>java.util.BitSet</c> is used in Java. /// <para/> /// Unlike <c>java.util.BitSet</c>, the fact that bits are packed into an array of longs /// is part of the interface. This allows efficient implementation of other algorithms /// by someone other than the author. It also allows one to efficiently implement /// alternate serialization or interchange formats. /// <para/> /// <see cref="OpenBitSet"/> is faster than <c>java.util.BitSet</c> in most operations /// and *much* faster at calculating cardinality of sets and results of set operations. /// It can also handle sets of larger cardinality (up to 64 * 2**32-1) /// <para/> /// The goals of <see cref="OpenBitSet"/> are the fastest implementation possible, and /// maximum code reuse. Extra safety and encapsulation /// may always be built on top, but if that's built in, the cost can never be removed (and /// hence people re-implement their own version in order to get better performance). /// <para/> /// <h3>Performance Results</h3> /// /// Test system: Pentium 4, Sun Java 1.5_06 -server -Xbatch -Xmx64M /// <para/>BitSet size = 1,000,000 /// <para/>Results are java.util.BitSet time divided by OpenBitSet time. /// <list type="table"> /// <listheader> /// <term></term> <term>cardinality</term> <term>IntersectionCount</term> <term>Union</term> <term>NextSetBit</term> <term>Get</term> <term>GetIterator</term> /// </listheader> /// <item> /// <term>50% full</term> <description>3.36</description> <description>3.96</description> <description>1.44</description> <description>1.46</description> <description>1.99</description> <description>1.58</description> /// </item> /// <item> /// <term>1% full</term> <description>3.31</description> <description>3.90</description> <description>&#160;</description> <description>1.04</description> <description>&#160;</description> <description>0.99</description> /// </item> /// </list> /// <para/> /// <para/> /// Test system: AMD Opteron, 64 bit linux, Sun Java 1.5_06 -server -Xbatch -Xmx64M /// <para/>BitSet size = 1,000,000 /// <para/>Results are java.util.BitSet time divided by OpenBitSet time. /// <list type="table"> /// <listheader> /// <term></term> <term>cardinality</term> <term>IntersectionCount</term> <term>Union</term> <term>NextSetBit</term> <term>Get</term> <term>GetIterator</term> /// </listheader> /// <item> /// <term>50% full</term> <description>2.50</description> <description>3.50</description> <description>1.00</description> <description>1.03</description> <description>1.12</description> <description>1.25</description> /// </item> /// <item> /// <term>1% full</term> <description>2.51</description> <description>3.49</description> <description>&#160;</description> <description>1.00</description> <description>&#160;</description> <description>1.02</description> /// </item> /// </list> /// </summary> public class OpenBitSet : DocIdSet, IBits #if FEATURE_CLONEABLE , System.ICloneable #endif { protected internal long[] m_bits; protected internal int m_wlen; // number of words (elements) used in the array // Used only for assert: private long numBits; /// <summary> /// Constructs an <see cref="OpenBitSet"/> large enough to hold <paramref name="numBits"/>. </summary> public OpenBitSet(long numBits) { this.numBits = numBits; m_bits = new long[Bits2words(numBits)]; m_wlen = m_bits.Length; } /// <summary> /// Constructor: allocates enough space for 64 bits. </summary> public OpenBitSet() : this(64) { } /// <summary> /// Constructs an <see cref="OpenBitSet"/> from an existing <see cref="T:long[]"/>. /// <para/> /// The first 64 bits are in long[0], with bit index 0 at the least significant /// bit, and bit index 63 at the most significant. Given a bit index, the word /// containing it is long[index/64], and it is at bit number index%64 within /// that word. /// <para/> /// <paramref name="numWords"/> are the number of elements in the array that contain set bits /// (non-zero longs). <paramref name="numWords"/> should be &lt;= bits.Length, and any existing /// words in the array at position &gt;= numWords should be zero. /// </summary> public OpenBitSet(long[] bits, int numWords) { if (numWords > bits.Length) { throw new ArgumentException("numWords cannot exceed bits.length"); } this.m_bits = bits; this.m_wlen = numWords; this.numBits = m_wlen * 64; } public override DocIdSetIterator GetIterator() { return new OpenBitSetIterator(m_bits, m_wlen); } public override IBits Bits => this; /// <summary> /// This DocIdSet implementation is cacheable. </summary> public override bool IsCacheable => true; /// <summary> /// Returns the current capacity in bits (1 greater than the index of the last bit). </summary> public virtual long Capacity => m_bits.Length << 6; // LUCENENET specific - eliminating this extra property, since it is identical to // Length anyway, and Length is required by the IBits interface. ///// <summary> ///// Returns the current capacity of this set. Included for ///// compatibility. this is *not* equal to <seealso cref="#cardinality"/>. ///// </summary> //public virtual long Size //{ // get { return Capacity; } //} /// <summary> /// Returns the current capacity of this set. This is *not* equal to <see cref="Cardinality()"/>. /// <para/> /// NOTE: This is equivalent to size() or length() in Lucene. /// </summary> public virtual int Length => m_bits.Length << 6; /// <summary> /// Returns <c>true</c> if there are no set bits </summary> public virtual bool IsEmpty => Cardinality() == 0; /// <summary> /// Expert: returns the <see cref="T:long[]"/> storing the bits. </summary> [WritableArray] public virtual long[] GetBits() { return m_bits; } /// <summary> /// Expert: gets the number of <see cref="long"/>s in the array that are in use. </summary> public virtual int NumWords => m_wlen; /// <summary> /// Returns <c>true</c> or <c>false</c> for the specified bit <paramref name="index"/>. </summary> public virtual bool Get(int index) { int i = index >> 6; // div 64 // signed shift will keep a negative index and force an // array-index-out-of-bounds-exception, removing the need for an explicit check. if (i >= m_bits.Length) { return false; } int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; return (m_bits[i] & bitmask) != 0; } /// <summary> /// Returns <c>true</c> or <c>false</c> for the specified bit <paramref name="index"/>. /// The index should be less than the <see cref="Length"/>. /// </summary> public virtual bool FastGet(int index) { Debug.Assert(index >= 0 && index < numBits); int i = index >> 6; // div 64 // signed shift will keep a negative index and force an // array-index-out-of-bounds-exception, removing the need for an explicit check. int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; return (m_bits[i] & bitmask) != 0; } /// <summary> /// Returns <c>true</c> or <c>false</c> for the specified bit <paramref name="index"/>. /// </summary> public virtual bool Get(long index) { int i = (int)(index >> 6); // div 64 if (i >= m_bits.Length) { return false; } int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; return (m_bits[i] & bitmask) != 0; } /// <summary> /// Returns <c>true</c> or <c>false</c> for the specified bit <paramref name="index"/>. /// The index should be less than the <see cref="Length"/>. /// </summary> public virtual bool FastGet(long index) { Debug.Assert(index >= 0 && index < numBits); int i = (int)(index >> 6); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; return (m_bits[i] & bitmask) != 0; } /* // alternate implementation of get() public boolean get1(int index) { int i = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 return ((bits[i]>>>bit) & 0x01) != 0; // this does a long shift and a bittest (on x86) vs // a long shift, and a long AND, (the test for zero is prob a no-op) // testing on a P4 indicates this is slower than (bits[i] & bitmask) != 0; } */ /// <summary> /// Returns 1 if the bit is set, 0 if not. /// The <paramref name="index"/> should be less than the <see cref="Length"/>. /// </summary> public virtual int GetBit(int index) { Debug.Assert(index >= 0 && index < numBits); int i = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 return ((int)((long)((ulong)m_bits[i] >> bit))) & 0x01; } /* public boolean get2(int index) { int word = index >> 6; // div 64 int bit = index & 0x0000003f; // mod 64 return (bits[word] << bit) < 0; // hmmm, this would work if bit order were reversed // we could right shift and check for parity bit, if it was available to us. } */ /// <summary> /// Sets a bit, expanding the set size if necessary. </summary> public virtual void Set(long index) { int wordNum = ExpandingWordNum(index); int bit = (int)index & 0x3f; long bitmask = 1L << bit; m_bits[wordNum] |= bitmask; } /// <summary> /// Sets the bit at the specified <paramref name="index"/>. /// The <paramref name="index"/> should be less than the <see cref="Length"/>. /// </summary> public virtual void FastSet(int index) { Debug.Assert(index >= 0 && index < numBits); int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; m_bits[wordNum] |= bitmask; } /// <summary> /// Sets the bit at the specified <paramref name="index"/>. /// The <paramref name="index"/> should be less than the <see cref="Length"/>. /// </summary> public virtual void FastSet(long index) { Debug.Assert(index >= 0 && index < numBits); int wordNum = (int)(index >> 6); int bit = (int)index & 0x3f; long bitmask = 1L << bit; m_bits[wordNum] |= bitmask; } /// <summary> /// Sets a range of bits, expanding the set size if necessary. /// </summary> /// <param name="startIndex"> Lower index </param> /// <param name="endIndex"> One-past the last bit to set </param> public virtual void Set(long startIndex, long endIndex) { if (endIndex <= startIndex) { return; } int startWord = (int)(startIndex >> 6); // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = ExpandingWordNum(endIndex - 1); long startmask = -1L << (int)startIndex; long endmask = (long)(0xffffffffffffffffUL >> (int)-endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap if (startWord == endWord) { m_bits[startWord] |= (startmask & endmask); return; } m_bits[startWord] |= startmask; Arrays.Fill(m_bits, startWord + 1, endWord, -1L); m_bits[endWord] |= endmask; } protected virtual int ExpandingWordNum(long index) { int wordNum = (int)(index >> 6); if (wordNum >= m_wlen) { EnsureCapacity(index + 1); } return wordNum; } /// <summary> /// Clears a bit. /// The <paramref name="index"/> should be less than the <see cref="Length"/>. /// </summary> public virtual void FastClear(int index) { Debug.Assert(index >= 0 && index < numBits); int wordNum = index >> 6; int bit = index & 0x03f; long bitmask = 1L << bit; m_bits[wordNum] &= ~bitmask; // hmmm, it takes one more instruction to clear than it does to set... any // way to work around this? If there were only 63 bits per word, we could // use a right shift of 10111111...111 in binary to position the 0 in the // correct place (using sign extension). // Could also use Long.rotateRight() or rotateLeft() *if* they were converted // by the JVM into a native instruction. // bits[word] &= Long.rotateLeft(0xfffffffe,bit); } /// <summary> /// Clears a bit. /// The <paramref name="index"/> should be less than the <see cref="Length"/>. /// </summary> public virtual void FastClear(long index) { Debug.Assert(index >= 0 && index < numBits); int wordNum = (int)(index >> 6); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; m_bits[wordNum] &= ~bitmask; } /// <summary> /// Clears a bit, allowing access beyond the current set size without changing the size. </summary> public virtual void Clear(long index) { int wordNum = (int)(index >> 6); // div 64 if (wordNum >= m_wlen) { return; } int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; m_bits[wordNum] &= ~bitmask; } /// <summary> /// Clears a range of bits. Clearing past the end does not change the size of the set. /// </summary> /// <param name="startIndex"> Lower index </param> /// <param name="endIndex"> One-past the last bit to clear </param> public virtual void Clear(int startIndex, int endIndex) { if (endIndex <= startIndex) { return; } int startWord = (startIndex >> 6); if (startWord >= m_wlen) { return; } // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = ((endIndex - 1) >> 6); long startmask = (-1L) << startIndex; // -1 << (startIndex mod 64) long endmask = (-1L) << endIndex; // -1 << (endIndex mod 64) if ((endIndex & 0x3f) == 0) { endmask = 0; } startmask = ~startmask; if (startWord == endWord) { m_bits[startWord] &= (startmask | endmask); return; } m_bits[startWord] &= startmask; int middle = Math.Min(m_wlen, endWord); Arrays.Fill(m_bits, startWord + 1, middle, 0L); if (endWord < m_wlen) { m_bits[endWord] &= endmask; } } /// <summary> /// Clears a range of bits. Clearing past the end does not change the size of the set. /// </summary> /// <param name="startIndex"> Lower index </param> /// <param name="endIndex"> One-past the last bit to clear </param> public virtual void Clear(long startIndex, long endIndex) { if (endIndex <= startIndex) { return; } int startWord = (int)(startIndex >> 6); if (startWord >= m_wlen) { return; } // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = (int)((endIndex - 1) >> 6); long startmask = -1L << (int)startIndex; long endmask = -(int)((uint)1L >> (int)-endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap // invert masks since we are clearing startmask = ~startmask; endmask = ~endmask; if (startWord == endWord) { m_bits[startWord] &= (startmask | endmask); return; } m_bits[startWord] &= startmask; int middle = Math.Min(m_wlen, endWord); Arrays.Fill(m_bits, startWord + 1, middle, 0L); if (endWord < m_wlen) { m_bits[endWord] &= endmask; } } /// <summary> /// Sets a bit and returns the previous value. /// The <paramref name="index"/> should be less than the <see cref="Length"/>. /// </summary> public virtual bool GetAndSet(int index) { Debug.Assert(index >= 0 && index < numBits); int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; bool val = (m_bits[wordNum] & bitmask) != 0; m_bits[wordNum] |= bitmask; return val; } /// <summary> /// Sets a bit and returns the previous value. /// The <paramref name="index"/> should be less than the <see cref="Length"/>. /// </summary> public virtual bool GetAndSet(long index) { Debug.Assert(index >= 0 && index < numBits); int wordNum = (int)(index >> 6); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; bool val = (m_bits[wordNum] & bitmask) != 0; m_bits[wordNum] |= bitmask; return val; } /// <summary> /// Flips a bit. /// The <paramref name="index"/> should be less than the <see cref="Length"/>. /// </summary> public virtual void FastFlip(int index) { Debug.Assert(index >= 0 && index < numBits); int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; m_bits[wordNum] ^= bitmask; } /// <summary> /// Flips a bit. /// The <paramref name="index"/> should be less than the <see cref="Length"/>. /// </summary> public virtual void FastFlip(long index) { Debug.Assert(index >= 0 && index < numBits); int wordNum = (int)(index >> 6); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; m_bits[wordNum] ^= bitmask; } /// <summary> /// Flips a bit, expanding the set size if necessary. </summary> public virtual void Flip(long index) { int wordNum = ExpandingWordNum(index); int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; m_bits[wordNum] ^= bitmask; } /// <summary> /// Flips a bit and returns the resulting bit value. /// The <paramref name="index"/> should be less than the <see cref="Length"/>. /// </summary> public virtual bool FlipAndGet(int index) { Debug.Assert(index >= 0 && index < numBits); int wordNum = index >> 6; // div 64 int bit = index & 0x3f; // mod 64 long bitmask = 1L << bit; m_bits[wordNum] ^= bitmask; return (m_bits[wordNum] & bitmask) != 0; } /// <summary> /// Flips a bit and returns the resulting bit value. /// The <paramref name="index"/> should be less than the <see cref="Length"/>. /// </summary> public virtual bool FlipAndGet(long index) { Debug.Assert(index >= 0 && index < numBits); int wordNum = (int)(index >> 6); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; m_bits[wordNum] ^= bitmask; return (m_bits[wordNum] & bitmask) != 0; } /// <summary> /// Flips a range of bits, expanding the set size if necessary. /// </summary> /// <param name="startIndex"> Lower index </param> /// <param name="endIndex"> One-past the last bit to flip </param> public virtual void Flip(long startIndex, long endIndex) { if (endIndex <= startIndex) { return; } int startWord = (int)(startIndex >> 6); // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = ExpandingWordNum(endIndex - 1); //* Grrr, java shifting wraps around so -1L>>>64 == -1 // for that reason, make sure not to use endmask if the bits to flip will // be zero in the last word (redefine endWord to be the last changed...) // long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000 // long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111 // ** long startmask = -1L << (int)startIndex; long endmask = (long)(0xffffffffffffffffUL >> (int)-endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap if (startWord == endWord) { m_bits[startWord] ^= (startmask & endmask); return; } m_bits[startWord] ^= startmask; for (int i = startWord + 1; i < endWord; i++) { m_bits[i] = ~m_bits[i]; } m_bits[endWord] ^= endmask; } /* public static int pop(long v0, long v1, long v2, long v3) { // derived from pop_array by setting last four elems to 0. // exchanges one pop() call for 10 elementary operations // saving about 7 instructions... is there a better way? long twosA=v0 & v1; long ones=v0^v1; long u2=ones^v2; long twosB =(ones&v2)|(u2&v3); ones=u2^v3; long fours=(twosA&twosB); long twos=twosA^twosB; return (pop(fours)<<2) + (pop(twos)<<1) + pop(ones); } */ /// <summary> /// Get the number of set bits. /// </summary> /// <returns> The number of set bits. </returns> public virtual long Cardinality() { return BitUtil.Pop_Array(m_bits, 0, m_wlen); } /// <summary> /// Returns the popcount or cardinality of the intersection of the two sets. /// Neither set is modified. /// </summary> public static long IntersectionCount(OpenBitSet a, OpenBitSet b) { return BitUtil.Pop_Intersect(a.m_bits, b.m_bits, 0, Math.Min(a.m_wlen, b.m_wlen)); } /// <summary> /// Returns the popcount or cardinality of the union of the two sets. /// Neither set is modified. /// </summary> public static long UnionCount(OpenBitSet a, OpenBitSet b) { long tot = BitUtil.Pop_Union(a.m_bits, b.m_bits, 0, Math.Min(a.m_wlen, b.m_wlen)); if (a.m_wlen < b.m_wlen) { tot += BitUtil.Pop_Array(b.m_bits, a.m_wlen, b.m_wlen - a.m_wlen); } else if (a.m_wlen > b.m_wlen) { tot += BitUtil.Pop_Array(a.m_bits, b.m_wlen, a.m_wlen - b.m_wlen); } return tot; } /// <summary> /// Returns the popcount or cardinality of "a and not b" /// or "intersection(a, not(b))". /// Neither set is modified. /// </summary> public static long AndNotCount(OpenBitSet a, OpenBitSet b) { long tot = BitUtil.Pop_AndNot(a.m_bits, b.m_bits, 0, Math.Min(a.m_wlen, b.m_wlen)); if (a.m_wlen > b.m_wlen) { tot += BitUtil.Pop_Array(a.m_bits, b.m_wlen, a.m_wlen - b.m_wlen); } return tot; } /// <summary> /// Returns the popcount or cardinality of the exclusive-or of the two sets. /// Neither set is modified. /// </summary> public static long XorCount(OpenBitSet a, OpenBitSet b) { long tot = BitUtil.Pop_Xor(a.m_bits, b.m_bits, 0, Math.Min(a.m_wlen, b.m_wlen)); if (a.m_wlen < b.m_wlen) { tot += BitUtil.Pop_Array(b.m_bits, a.m_wlen, b.m_wlen - a.m_wlen); } else if (a.m_wlen > b.m_wlen) { tot += BitUtil.Pop_Array(a.m_bits, b.m_wlen, a.m_wlen - b.m_wlen); } return tot; } /// <summary> /// Returns the index of the first set bit starting at the <paramref name="index"/> specified. /// -1 is returned if there are no more set bits. /// </summary> public virtual int NextSetBit(int index) { int i = index >> 6; if (i >= m_wlen) { return -1; } int subIndex = index & 0x3f; // index within the word long word = m_bits[i] >> subIndex; // skip all the bits to the right of index if (word != 0) { return (i << 6) + subIndex + word.TrailingZeroCount(); } while (++i < m_wlen) { word = m_bits[i]; if (word != 0) { return (i << 6) + word.TrailingZeroCount(); } } return -1; } /// <summary> /// Returns the index of the first set bit starting at the <paramref name="index"/> specified. /// -1 is returned if there are no more set bits. /// </summary> public virtual long NextSetBit(long index) { int i = (int)((long)((ulong)index >> 6)); if (i >= m_wlen) { return -1; } int subIndex = (int)index & 0x3f; // index within the word long word = (long)((ulong)m_bits[i] >> subIndex); // skip all the bits to the right of index if (word != 0) { return (((long)i) << 6) + (subIndex + word.TrailingZeroCount()); } while (++i < m_wlen) { word = m_bits[i]; if (word != 0) { return (((long)i) << 6) + word.TrailingZeroCount(); } } return -1; } /// <summary> /// Returns the index of the first set bit starting downwards at /// the <paramref name="index"/> specified. /// -1 is returned if there are no more set bits. /// </summary> public virtual int PrevSetBit(int index) { int i = index >> 6; int subIndex; long word; if (i >= m_wlen) { i = m_wlen - 1; if (i < 0) { return -1; } subIndex = 63; // last possible bit word = m_bits[i]; } else { if (i < 0) { return -1; } subIndex = index & 0x3f; // index within the word word = (m_bits[i] << (63 - subIndex)); // skip all the bits to the left of index } if (word != 0) { return (i << 6) + subIndex - word.LeadingZeroCount(); // See LUCENE-3197 } while (--i >= 0) { word = m_bits[i]; if (word != 0) { return (i << 6) + 63 - word.LeadingZeroCount(); } } return -1; } /// <summary> /// Returns the index of the first set bit starting downwards at /// the <paramref name="index"/> specified. /// -1 is returned if there are no more set bits. /// </summary> public virtual long PrevSetBit(long index) { int i = (int)(index >> 6); int subIndex; long word; if (i >= m_wlen) { i = m_wlen - 1; if (i < 0) { return -1; } subIndex = 63; // last possible bit word = m_bits[i]; } else { if (i < 0) { return -1; } subIndex = (int)index & 0x3f; // index within the word word = (m_bits[i] << (63 - subIndex)); // skip all the bits to the left of index } if (word != 0) { return (((long)i) << 6) + subIndex - word.LeadingZeroCount(); // See LUCENE-3197 } while (--i >= 0) { word = m_bits[i]; if (word != 0) { return (((long)i) << 6) + 63 - word.LeadingZeroCount(); } } return -1; } public object Clone() { //OpenBitSet obs = (OpenBitSet)base.Clone(); //obs.bits = (long[])obs.bits.Clone(); // hopefully an array clone is as fast(er) than arraycopy OpenBitSet obs = new OpenBitSet((long[])m_bits.Clone(), m_wlen); return obs; } /// <summary> /// this = this AND other </summary> public virtual void Intersect(OpenBitSet other) { int newLen = Math.Min(this.m_wlen, other.m_wlen); long[] thisArr = this.m_bits; long[] otherArr = other.m_bits; // testing against zero can be more efficient int pos = newLen; while (--pos >= 0) { thisArr[pos] &= otherArr[pos]; } if (this.m_wlen > newLen) { // fill zeros from the new shorter length to the old length Arrays.Fill(m_bits, newLen, this.m_wlen, 0); } this.m_wlen = newLen; } /// <summary> /// this = this OR other </summary> public virtual void Union(OpenBitSet other) { int newLen = Math.Max(m_wlen, other.m_wlen); // LUCENENET specific: Since EnsureCapacityWords // sets m_wlen, we need to save the value here to ensure the // tail of the array is copied. Also removed the double-set // after Array.Copy. // https://github.com/apache/lucenenet/pull/154 int oldLen = m_wlen; EnsureCapacityWords(newLen); Debug.Assert((numBits = Math.Max(other.numBits, numBits)) >= 0); long[] thisArr = this.m_bits; long[] otherArr = other.m_bits; int pos = Math.Min(oldLen, other.m_wlen); while (--pos >= 0) { thisArr[pos] |= otherArr[pos]; } if (oldLen < newLen) { Array.Copy(otherArr, oldLen, thisArr, oldLen, newLen - oldLen); } } /// <summary> /// Remove all elements set in other. this = this AND_NOT other. </summary> public virtual void Remove(OpenBitSet other) { int idx = Math.Min(m_wlen, other.m_wlen); long[] thisArr = this.m_bits; long[] otherArr = other.m_bits; while (--idx >= 0) { thisArr[idx] &= ~otherArr[idx]; } } /// <summary> /// this = this XOR other </summary> public virtual void Xor(OpenBitSet other) { int newLen = Math.Max(m_wlen, other.m_wlen); // LUCENENET specific: Since EnsureCapacityWords // sets m_wlen, we need to save the value here to ensure the // tail of the array is copied. Also removed the double-set // after Array.Copy. // https://github.com/apache/lucenenet/pull/154 int oldLen = m_wlen; EnsureCapacityWords(newLen); Debug.Assert((numBits = Math.Max(other.numBits, numBits)) >= 0); long[] thisArr = this.m_bits; long[] otherArr = other.m_bits; int pos = Math.Min(oldLen, other.m_wlen); while (--pos >= 0) { thisArr[pos] ^= otherArr[pos]; } if (oldLen < newLen) { Array.Copy(otherArr, oldLen, thisArr, oldLen, newLen - oldLen); } } // some BitSet compatability methods /// <summary>see <see cref="Intersect(OpenBitSet)"/></summary> public virtual void And(OpenBitSet other) { Intersect(other); } /// <summary>see <see cref="Union(OpenBitSet)"/></summary> public virtual void Or(OpenBitSet other) { Union(other); } /// <summary>see <see cref="AndNot(OpenBitSet)"/></summary> public virtual void AndNot(OpenBitSet other) { Remove(other); } /// <summary> /// returns <c>true</c> if the sets have any elements in common. </summary> public virtual bool Intersects(OpenBitSet other) { int pos = Math.Min(this.m_wlen, other.m_wlen); long[] thisArr = this.m_bits; long[] otherArr = other.m_bits; while (--pos >= 0) { if ((thisArr[pos] & otherArr[pos]) != 0) { return true; } } return false; } /// <summary> /// Expand the <see cref="T:long[]"/> with the size given as a number of words (64 bit longs). </summary> public virtual void EnsureCapacityWords(int numWords) { m_bits = ArrayUtil.Grow(m_bits, numWords); m_wlen = numWords; Debug.Assert((this.numBits = Math.Max(this.numBits, numWords << 6)) >= 0); } /// <summary> /// Ensure that the <see cref="T:long[]"/> is big enough to hold numBits, expanding it if /// necessary. /// </summary> public virtual void EnsureCapacity(long numBits) { EnsureCapacityWords(Bits2words(numBits)); // ensureCapacityWords sets numBits to a multiple of 64, but we want to set // it to exactly what the app asked. Debug.Assert((this.numBits = Math.Max(this.numBits, numBits)) >= 0); } /// <summary> /// Lowers numWords, the number of words in use, /// by checking for trailing zero words. /// </summary> public virtual void TrimTrailingZeros() { int idx = m_wlen - 1; while (idx >= 0 && m_bits[idx] == 0) { idx--; } m_wlen = idx + 1; } /// <summary> /// Returns the number of 64 bit words it would take to hold <paramref name="numBits"/>. </summary> public static int Bits2words(long numBits) { return (int)(((numBits - 1) >> 6) + 1); } /// <summary> /// Returns <c>true</c> if both sets have the same bits set. </summary> public override bool Equals(object o) { if (this == o) { return true; } if (!(o is OpenBitSet)) { return false; } OpenBitSet a; OpenBitSet b = (OpenBitSet)o; // make a the larger set. if (b.m_wlen > this.m_wlen) { a = b; b = this; } else { a = this; } // check for any set bits out of the range of b for (int i = a.m_wlen - 1; i >= b.m_wlen; i--) { if (a.m_bits[i] != 0) { return false; } } for (int i = b.m_wlen - 1; i >= 0; i--) { if (a.m_bits[i] != b.m_bits[i]) { return false; } } return true; } public override int GetHashCode() { // Start with a zero hash and use a mix that results in zero if the input is zero. // this effectively truncates trailing zeros without an explicit check. long h = 0; for (int i = m_bits.Length; --i >= 0; ) { h ^= m_bits[i]; h = (h << 1) | ((long)((ulong)h >> 63)); // rotate left } // fold leftmost bits into right and add a constant to prevent // empty sets from returning 0, which is too common. return (int)((h >> 32) ^ h) + unchecked((int)0x98761234); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Home Groups Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KGCDataSet : EduHubDataSet<KGC> { /// <inheritdoc /> public override string Name { get { return "KGC"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KGCDataSet(EduHubContext Context) : base(Context) { Index_CAMPUS = new Lazy<NullDictionary<int?, IReadOnlyList<KGC>>>(() => this.ToGroupedNullDictionary(i => i.CAMPUS)); Index_KGCKEY = new Lazy<Dictionary<string, KGC>>(() => this.ToDictionary(i => i.KGCKEY)); Index_MAX_AC_YR = new Lazy<NullDictionary<string, IReadOnlyList<KGC>>>(() => this.ToGroupedNullDictionary(i => i.MAX_AC_YR)); Index_MIN_AC_YR = new Lazy<NullDictionary<string, IReadOnlyList<KGC>>>(() => this.ToGroupedNullDictionary(i => i.MIN_AC_YR)); Index_NEXT_HG = new Lazy<NullDictionary<string, IReadOnlyList<KGC>>>(() => this.ToGroupedNullDictionary(i => i.NEXT_HG)); Index_ROOM = new Lazy<NullDictionary<string, IReadOnlyList<KGC>>>(() => this.ToGroupedNullDictionary(i => i.ROOM)); Index_TEACHER = new Lazy<NullDictionary<string, IReadOnlyList<KGC>>>(() => this.ToGroupedNullDictionary(i => i.TEACHER)); Index_TEACHER_B = new Lazy<NullDictionary<string, IReadOnlyList<KGC>>>(() => this.ToGroupedNullDictionary(i => i.TEACHER_B)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KGC" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KGC" /> fields for each CSV column header</returns> internal override Action<KGC, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KGC, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KGCKEY": mapper[i] = (e, v) => e.KGCKEY = v; break; case "DESCRIPTION": mapper[i] = (e, v) => e.DESCRIPTION = v; break; case "CAMPUS": mapper[i] = (e, v) => e.CAMPUS = v == null ? (int?)null : int.Parse(v); break; case "TEACHER": mapper[i] = (e, v) => e.TEACHER = v; break; case "TEACHER_B": mapper[i] = (e, v) => e.TEACHER_B = v; break; case "ACTIVE": mapper[i] = (e, v) => e.ACTIVE = v; break; case "ROOM": mapper[i] = (e, v) => e.ROOM = v; break; case "HG_SIZE": mapper[i] = (e, v) => e.HG_SIZE = v == null ? (short?)null : short.Parse(v); break; case "MALES": mapper[i] = (e, v) => e.MALES = v == null ? (short?)null : short.Parse(v); break; case "FEMALES": mapper[i] = (e, v) => e.FEMALES = v == null ? (short?)null : short.Parse(v); break; case "MIN_AC_YR": mapper[i] = (e, v) => e.MIN_AC_YR = v; break; case "MAX_AC_YR": mapper[i] = (e, v) => e.MAX_AC_YR = v; break; case "NEXT_HG": mapper[i] = (e, v) => e.NEXT_HG = v; break; case "SELF_DESCRIBED": mapper[i] = (e, v) => e.SELF_DESCRIBED = v == null ? (short?)null : short.Parse(v); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KGC" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KGC" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KGC" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KGC}"/> of entities</returns> internal override IEnumerable<KGC> ApplyDeltaEntities(IEnumerable<KGC> Entities, List<KGC> DeltaEntities) { HashSet<string> Index_KGCKEY = new HashSet<string>(DeltaEntities.Select(i => i.KGCKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KGCKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KGCKEY.Remove(entity.KGCKEY); if (entity.KGCKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<int?, IReadOnlyList<KGC>>> Index_CAMPUS; private Lazy<Dictionary<string, KGC>> Index_KGCKEY; private Lazy<NullDictionary<string, IReadOnlyList<KGC>>> Index_MAX_AC_YR; private Lazy<NullDictionary<string, IReadOnlyList<KGC>>> Index_MIN_AC_YR; private Lazy<NullDictionary<string, IReadOnlyList<KGC>>> Index_NEXT_HG; private Lazy<NullDictionary<string, IReadOnlyList<KGC>>> Index_ROOM; private Lazy<NullDictionary<string, IReadOnlyList<KGC>>> Index_TEACHER; private Lazy<NullDictionary<string, IReadOnlyList<KGC>>> Index_TEACHER_B; #endregion #region Index Methods /// <summary> /// Find KGC by CAMPUS field /// </summary> /// <param name="CAMPUS">CAMPUS value used to find KGC</param> /// <returns>List of related KGC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> FindByCAMPUS(int? CAMPUS) { return Index_CAMPUS.Value[CAMPUS]; } /// <summary> /// Attempt to find KGC by CAMPUS field /// </summary> /// <param name="CAMPUS">CAMPUS value used to find KGC</param> /// <param name="Value">List of related KGC entities</param> /// <returns>True if the list of related KGC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCAMPUS(int? CAMPUS, out IReadOnlyList<KGC> Value) { return Index_CAMPUS.Value.TryGetValue(CAMPUS, out Value); } /// <summary> /// Attempt to find KGC by CAMPUS field /// </summary> /// <param name="CAMPUS">CAMPUS value used to find KGC</param> /// <returns>List of related KGC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> TryFindByCAMPUS(int? CAMPUS) { IReadOnlyList<KGC> value; if (Index_CAMPUS.Value.TryGetValue(CAMPUS, out value)) { return value; } else { return null; } } /// <summary> /// Find KGC by KGCKEY field /// </summary> /// <param name="KGCKEY">KGCKEY value used to find KGC</param> /// <returns>Related KGC entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KGC FindByKGCKEY(string KGCKEY) { return Index_KGCKEY.Value[KGCKEY]; } /// <summary> /// Attempt to find KGC by KGCKEY field /// </summary> /// <param name="KGCKEY">KGCKEY value used to find KGC</param> /// <param name="Value">Related KGC entity</param> /// <returns>True if the related KGC entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKGCKEY(string KGCKEY, out KGC Value) { return Index_KGCKEY.Value.TryGetValue(KGCKEY, out Value); } /// <summary> /// Attempt to find KGC by KGCKEY field /// </summary> /// <param name="KGCKEY">KGCKEY value used to find KGC</param> /// <returns>Related KGC entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KGC TryFindByKGCKEY(string KGCKEY) { KGC value; if (Index_KGCKEY.Value.TryGetValue(KGCKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find KGC by MAX_AC_YR field /// </summary> /// <param name="MAX_AC_YR">MAX_AC_YR value used to find KGC</param> /// <returns>List of related KGC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> FindByMAX_AC_YR(string MAX_AC_YR) { return Index_MAX_AC_YR.Value[MAX_AC_YR]; } /// <summary> /// Attempt to find KGC by MAX_AC_YR field /// </summary> /// <param name="MAX_AC_YR">MAX_AC_YR value used to find KGC</param> /// <param name="Value">List of related KGC entities</param> /// <returns>True if the list of related KGC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByMAX_AC_YR(string MAX_AC_YR, out IReadOnlyList<KGC> Value) { return Index_MAX_AC_YR.Value.TryGetValue(MAX_AC_YR, out Value); } /// <summary> /// Attempt to find KGC by MAX_AC_YR field /// </summary> /// <param name="MAX_AC_YR">MAX_AC_YR value used to find KGC</param> /// <returns>List of related KGC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> TryFindByMAX_AC_YR(string MAX_AC_YR) { IReadOnlyList<KGC> value; if (Index_MAX_AC_YR.Value.TryGetValue(MAX_AC_YR, out value)) { return value; } else { return null; } } /// <summary> /// Find KGC by MIN_AC_YR field /// </summary> /// <param name="MIN_AC_YR">MIN_AC_YR value used to find KGC</param> /// <returns>List of related KGC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> FindByMIN_AC_YR(string MIN_AC_YR) { return Index_MIN_AC_YR.Value[MIN_AC_YR]; } /// <summary> /// Attempt to find KGC by MIN_AC_YR field /// </summary> /// <param name="MIN_AC_YR">MIN_AC_YR value used to find KGC</param> /// <param name="Value">List of related KGC entities</param> /// <returns>True if the list of related KGC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByMIN_AC_YR(string MIN_AC_YR, out IReadOnlyList<KGC> Value) { return Index_MIN_AC_YR.Value.TryGetValue(MIN_AC_YR, out Value); } /// <summary> /// Attempt to find KGC by MIN_AC_YR field /// </summary> /// <param name="MIN_AC_YR">MIN_AC_YR value used to find KGC</param> /// <returns>List of related KGC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> TryFindByMIN_AC_YR(string MIN_AC_YR) { IReadOnlyList<KGC> value; if (Index_MIN_AC_YR.Value.TryGetValue(MIN_AC_YR, out value)) { return value; } else { return null; } } /// <summary> /// Find KGC by NEXT_HG field /// </summary> /// <param name="NEXT_HG">NEXT_HG value used to find KGC</param> /// <returns>List of related KGC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> FindByNEXT_HG(string NEXT_HG) { return Index_NEXT_HG.Value[NEXT_HG]; } /// <summary> /// Attempt to find KGC by NEXT_HG field /// </summary> /// <param name="NEXT_HG">NEXT_HG value used to find KGC</param> /// <param name="Value">List of related KGC entities</param> /// <returns>True if the list of related KGC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByNEXT_HG(string NEXT_HG, out IReadOnlyList<KGC> Value) { return Index_NEXT_HG.Value.TryGetValue(NEXT_HG, out Value); } /// <summary> /// Attempt to find KGC by NEXT_HG field /// </summary> /// <param name="NEXT_HG">NEXT_HG value used to find KGC</param> /// <returns>List of related KGC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> TryFindByNEXT_HG(string NEXT_HG) { IReadOnlyList<KGC> value; if (Index_NEXT_HG.Value.TryGetValue(NEXT_HG, out value)) { return value; } else { return null; } } /// <summary> /// Find KGC by ROOM field /// </summary> /// <param name="ROOM">ROOM value used to find KGC</param> /// <returns>List of related KGC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> FindByROOM(string ROOM) { return Index_ROOM.Value[ROOM]; } /// <summary> /// Attempt to find KGC by ROOM field /// </summary> /// <param name="ROOM">ROOM value used to find KGC</param> /// <param name="Value">List of related KGC entities</param> /// <returns>True if the list of related KGC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByROOM(string ROOM, out IReadOnlyList<KGC> Value) { return Index_ROOM.Value.TryGetValue(ROOM, out Value); } /// <summary> /// Attempt to find KGC by ROOM field /// </summary> /// <param name="ROOM">ROOM value used to find KGC</param> /// <returns>List of related KGC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> TryFindByROOM(string ROOM) { IReadOnlyList<KGC> value; if (Index_ROOM.Value.TryGetValue(ROOM, out value)) { return value; } else { return null; } } /// <summary> /// Find KGC by TEACHER field /// </summary> /// <param name="TEACHER">TEACHER value used to find KGC</param> /// <returns>List of related KGC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> FindByTEACHER(string TEACHER) { return Index_TEACHER.Value[TEACHER]; } /// <summary> /// Attempt to find KGC by TEACHER field /// </summary> /// <param name="TEACHER">TEACHER value used to find KGC</param> /// <param name="Value">List of related KGC entities</param> /// <returns>True if the list of related KGC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTEACHER(string TEACHER, out IReadOnlyList<KGC> Value) { return Index_TEACHER.Value.TryGetValue(TEACHER, out Value); } /// <summary> /// Attempt to find KGC by TEACHER field /// </summary> /// <param name="TEACHER">TEACHER value used to find KGC</param> /// <returns>List of related KGC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> TryFindByTEACHER(string TEACHER) { IReadOnlyList<KGC> value; if (Index_TEACHER.Value.TryGetValue(TEACHER, out value)) { return value; } else { return null; } } /// <summary> /// Find KGC by TEACHER_B field /// </summary> /// <param name="TEACHER_B">TEACHER_B value used to find KGC</param> /// <returns>List of related KGC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> FindByTEACHER_B(string TEACHER_B) { return Index_TEACHER_B.Value[TEACHER_B]; } /// <summary> /// Attempt to find KGC by TEACHER_B field /// </summary> /// <param name="TEACHER_B">TEACHER_B value used to find KGC</param> /// <param name="Value">List of related KGC entities</param> /// <returns>True if the list of related KGC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTEACHER_B(string TEACHER_B, out IReadOnlyList<KGC> Value) { return Index_TEACHER_B.Value.TryGetValue(TEACHER_B, out Value); } /// <summary> /// Attempt to find KGC by TEACHER_B field /// </summary> /// <param name="TEACHER_B">TEACHER_B value used to find KGC</param> /// <returns>List of related KGC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGC> TryFindByTEACHER_B(string TEACHER_B) { IReadOnlyList<KGC> value; if (Index_TEACHER_B.Value.TryGetValue(TEACHER_B, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KGC table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KGC]( [KGCKEY] varchar(3) NOT NULL, [DESCRIPTION] varchar(30) NULL, [CAMPUS] int NULL, [TEACHER] varchar(4) NULL, [TEACHER_B] varchar(4) NULL, [ACTIVE] varchar(1) NULL, [ROOM] varchar(4) NULL, [HG_SIZE] smallint NULL, [MALES] smallint NULL, [FEMALES] smallint NULL, [MIN_AC_YR] varchar(4) NULL, [MAX_AC_YR] varchar(4) NULL, [NEXT_HG] varchar(3) NULL, [SELF_DESCRIBED] smallint NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KGC_Index_KGCKEY] PRIMARY KEY CLUSTERED ( [KGCKEY] ASC ) ); CREATE NONCLUSTERED INDEX [KGC_Index_CAMPUS] ON [dbo].[KGC] ( [CAMPUS] ASC ); CREATE NONCLUSTERED INDEX [KGC_Index_MAX_AC_YR] ON [dbo].[KGC] ( [MAX_AC_YR] ASC ); CREATE NONCLUSTERED INDEX [KGC_Index_MIN_AC_YR] ON [dbo].[KGC] ( [MIN_AC_YR] ASC ); CREATE NONCLUSTERED INDEX [KGC_Index_NEXT_HG] ON [dbo].[KGC] ( [NEXT_HG] ASC ); CREATE NONCLUSTERED INDEX [KGC_Index_ROOM] ON [dbo].[KGC] ( [ROOM] ASC ); CREATE NONCLUSTERED INDEX [KGC_Index_TEACHER] ON [dbo].[KGC] ( [TEACHER] ASC ); CREATE NONCLUSTERED INDEX [KGC_Index_TEACHER_B] ON [dbo].[KGC] ( [TEACHER_B] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_CAMPUS') ALTER INDEX [KGC_Index_CAMPUS] ON [dbo].[KGC] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_MAX_AC_YR') ALTER INDEX [KGC_Index_MAX_AC_YR] ON [dbo].[KGC] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_MIN_AC_YR') ALTER INDEX [KGC_Index_MIN_AC_YR] ON [dbo].[KGC] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_NEXT_HG') ALTER INDEX [KGC_Index_NEXT_HG] ON [dbo].[KGC] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_ROOM') ALTER INDEX [KGC_Index_ROOM] ON [dbo].[KGC] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_TEACHER') ALTER INDEX [KGC_Index_TEACHER] ON [dbo].[KGC] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_TEACHER_B') ALTER INDEX [KGC_Index_TEACHER_B] ON [dbo].[KGC] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_CAMPUS') ALTER INDEX [KGC_Index_CAMPUS] ON [dbo].[KGC] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_MAX_AC_YR') ALTER INDEX [KGC_Index_MAX_AC_YR] ON [dbo].[KGC] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_MIN_AC_YR') ALTER INDEX [KGC_Index_MIN_AC_YR] ON [dbo].[KGC] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_NEXT_HG') ALTER INDEX [KGC_Index_NEXT_HG] ON [dbo].[KGC] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_ROOM') ALTER INDEX [KGC_Index_ROOM] ON [dbo].[KGC] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_TEACHER') ALTER INDEX [KGC_Index_TEACHER] ON [dbo].[KGC] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGC]') AND name = N'KGC_Index_TEACHER_B') ALTER INDEX [KGC_Index_TEACHER_B] ON [dbo].[KGC] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KGC"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KGC"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KGC> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_KGCKEY = new List<string>(); foreach (var entity in Entities) { Index_KGCKEY.Add(entity.KGCKEY); } builder.AppendLine("DELETE [dbo].[KGC] WHERE"); // Index_KGCKEY builder.Append("[KGCKEY] IN ("); for (int index = 0; index < Index_KGCKEY.Count; index++) { if (index != 0) builder.Append(", "); // KGCKEY var parameterKGCKEY = $"@p{parameterIndex++}"; builder.Append(parameterKGCKEY); command.Parameters.Add(parameterKGCKEY, SqlDbType.VarChar, 3).Value = Index_KGCKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KGC data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KGC data set</returns> public override EduHubDataSetDataReader<KGC> GetDataSetDataReader() { return new KGCDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KGC data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KGC data set</returns> public override EduHubDataSetDataReader<KGC> GetDataSetDataReader(List<KGC> Entities) { return new KGCDataReader(new EduHubDataSetLoadedReader<KGC>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KGCDataReader : EduHubDataSetDataReader<KGC> { public KGCDataReader(IEduHubDataSetReader<KGC> Reader) : base (Reader) { } public override int FieldCount { get { return 17; } } public override object GetValue(int i) { switch (i) { case 0: // KGCKEY return Current.KGCKEY; case 1: // DESCRIPTION return Current.DESCRIPTION; case 2: // CAMPUS return Current.CAMPUS; case 3: // TEACHER return Current.TEACHER; case 4: // TEACHER_B return Current.TEACHER_B; case 5: // ACTIVE return Current.ACTIVE; case 6: // ROOM return Current.ROOM; case 7: // HG_SIZE return Current.HG_SIZE; case 8: // MALES return Current.MALES; case 9: // FEMALES return Current.FEMALES; case 10: // MIN_AC_YR return Current.MIN_AC_YR; case 11: // MAX_AC_YR return Current.MAX_AC_YR; case 12: // NEXT_HG return Current.NEXT_HG; case 13: // SELF_DESCRIBED return Current.SELF_DESCRIBED; case 14: // LW_DATE return Current.LW_DATE; case 15: // LW_TIME return Current.LW_TIME; case 16: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // DESCRIPTION return Current.DESCRIPTION == null; case 2: // CAMPUS return Current.CAMPUS == null; case 3: // TEACHER return Current.TEACHER == null; case 4: // TEACHER_B return Current.TEACHER_B == null; case 5: // ACTIVE return Current.ACTIVE == null; case 6: // ROOM return Current.ROOM == null; case 7: // HG_SIZE return Current.HG_SIZE == null; case 8: // MALES return Current.MALES == null; case 9: // FEMALES return Current.FEMALES == null; case 10: // MIN_AC_YR return Current.MIN_AC_YR == null; case 11: // MAX_AC_YR return Current.MAX_AC_YR == null; case 12: // NEXT_HG return Current.NEXT_HG == null; case 13: // SELF_DESCRIBED return Current.SELF_DESCRIBED == null; case 14: // LW_DATE return Current.LW_DATE == null; case 15: // LW_TIME return Current.LW_TIME == null; case 16: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KGCKEY return "KGCKEY"; case 1: // DESCRIPTION return "DESCRIPTION"; case 2: // CAMPUS return "CAMPUS"; case 3: // TEACHER return "TEACHER"; case 4: // TEACHER_B return "TEACHER_B"; case 5: // ACTIVE return "ACTIVE"; case 6: // ROOM return "ROOM"; case 7: // HG_SIZE return "HG_SIZE"; case 8: // MALES return "MALES"; case 9: // FEMALES return "FEMALES"; case 10: // MIN_AC_YR return "MIN_AC_YR"; case 11: // MAX_AC_YR return "MAX_AC_YR"; case 12: // NEXT_HG return "NEXT_HG"; case 13: // SELF_DESCRIBED return "SELF_DESCRIBED"; case 14: // LW_DATE return "LW_DATE"; case 15: // LW_TIME return "LW_TIME"; case 16: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KGCKEY": return 0; case "DESCRIPTION": return 1; case "CAMPUS": return 2; case "TEACHER": return 3; case "TEACHER_B": return 4; case "ACTIVE": return 5; case "ROOM": return 6; case "HG_SIZE": return 7; case "MALES": return 8; case "FEMALES": return 9; case "MIN_AC_YR": return 10; case "MAX_AC_YR": return 11; case "NEXT_HG": return 12; case "SELF_DESCRIBED": return 13; case "LW_DATE": return 14; case "LW_TIME": return 15; case "LW_USER": return 16; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq.Expressions; using System.Reflection; using System.Text; using Antlr.Runtime; using ExpressionEvaluator; using ExpressionEvaluator.Parser.Expressions; namespace ExpressionEvaluator.Parser { public partial class ExprEvalParser { private CompilerState compilerState = new CompilerState(); public Expression Scope { get; set; } public bool IsCall { get; set; } public LabelTarget ReturnTarget { get; set; } public bool HasReturn { get; private set; } public TypeRegistry TypeRegistry { get; set; } public Dictionary<string, Type> DynamicTypeLookup { get; set; } private Stack<TypeOrGeneric> methodStack = new Stack<TypeOrGeneric>(); //partial void EnterRule(string ruleName, int ruleIndex) //{ // base.TraceIn(ruleName, ruleIndex); // Debug.WriteLine("In: {0} {1}", ruleName, ruleIndex); //} //partial void LeaveRule(string ruleName, int ruleIndex) //{ // Debug.WriteLine("Out: {0} {1}", ruleName, ruleIndex); //} //protected Type GetPropertyType(Expression expression, string propertyName) //{ // var pe = (ParameterExpression) expression; // var methodInfo = pe.Type.GetMethod("getType", BindingFlags.Instance); // if (methodInfo != null) // { // return (Type)methodInfo.Invoke(pe., new object[] { propertyName }); // } // return null; //} public object Eval(string expressionString) { var ms = new MemoryStream(Encoding.UTF8.GetBytes(expressionString)); var input = new ANTLRInputStream(ms); var lexer = new ExprEvalLexer(input); var tokens = new TokenRewriteStream(lexer); if (TypeRegistry == null) TypeRegistry = new TypeRegistry(); var parser = new ExprEvalParser(tokens) { TypeRegistry = TypeRegistry, Scope = Scope, IsCall = IsCall, DynamicTypeLookup = DynamicTypeLookup }; Expression expression = parser.single_expression(); if (expression == null) { var statement = parser.statement(); if (statement != null) { expression = statement.Expression; } if (expression == null) { var statements = parser.statement_list(); expression = statements.ToBlock(); } } if (Scope != null) { var func = Expression.Lambda<Func<object, object>>(Expression.Convert(expression, typeof(Object)), new ParameterExpression[] { (ParameterExpression)Scope }).Compile(); return func(Scope); } else { var func = Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(Object))).Compile(); return func(); } } protected Expression GetPrimaryExpressionPart(PrimaryExpressionPart primary_expression_part2, ITokenStream input, Expression value, bool throwsException = true) { if (primary_expression_part2.GetType() == typeof(AccessIdentifier)) { if (input.LT(1).Text == "(") { methodStack.Push(((AccessIdentifier)primary_expression_part2).Value); } else { var memberName = ((AccessIdentifier)primary_expression_part2).Value.Identifier; try { var newValue = ExpressionHelper.GetProperty(value, memberName); if (newValue == null && throwsException) { throw new ExpressionParseException(string.Format("Cannot resolve member \"{0}\" on type \"{1}\"", memberName, value.Type.Name), input); //throw new ExpressionParseException(string.Format("Cannot resolve symbol \"{0}\"", input.LT(-1).Text), input); } value = newValue; } catch (ExpressionContainerException ex) { value = ExpressionHelper.MethodInvokeExpression(typeof(ExprEvalParser), Expression.Constant(this), new TypeOrGeneric() { Identifier = "Eval" }, new Argument[] { new Argument() { Expression = ex.Container } }); } } } else if (primary_expression_part2.GetType() == typeof(Brackets)) { value = ExpressionHelper.GetPropertyIndex(value, ((Brackets)primary_expression_part2).Values); } else if (primary_expression_part2.GetType() == typeof(Arguments)) { if (methodStack.Count > 0) { var method = methodStack.Pop(); var newValue = ExpressionHelper.GetMethod(value, method, ((Arguments)primary_expression_part2).Values, false); if (newValue == null && throwsException) { throw new ExpressionParseException(string.Format("Cannot resolve member \"{0}\" on type \"{1}\"", method.Identifier, value.Type.Name), input); //throw new ExpressionParseException(string.Format("Cannot resolve symbol \"{0}\"", input.LT(-1).Text), input); } value = newValue; } else { // value = GetMethod(value, membername, ((Arguments)primary_expression_part2).Values); } } else if (primary_expression_part2.GetType() == typeof(PostIncrement)) { value = Expression.Assign(value, Expression.Increment(value)); } else if (primary_expression_part2.GetType() == typeof(PostDecrement)) { value = Expression.Assign(value, Expression.Decrement(value)); } return value; } public override void ReportError(RecognitionException e) { base.ReportError(e); string message; if (e.GetType() == typeof(MismatchedTokenException)) { var ex = (MismatchedTokenException)e; message = string.Format("Mismatched token '{0}', expected {1}", e.Token.Text, ex.Expecting); } else { message = string.Format("Error parsing token '{0}'", e.Token.Text); } throw new ExpressionParseException(message, input); Console.WriteLine("Error in parser at line " + e.Line + ":" + e.CharPositionInLine); } private Expression GetIdentifier(string identifier) { ParameterExpression parameter; if (ParameterList.TryGetValue(identifier, out parameter)) { return parameter; } object result = null; if (TypeRegistry.TryGetValue(identifier, out result)) { if (result.GetType() == typeof(ValueType)) { var typeValue = (ValueType)result; return Expression.Constant(typeValue.Value, typeValue.Type); } if (result.GetType() == typeof(DelegateType)) { var typeValue = (DelegateType)result; return Expression.Constant(typeValue.Value(), typeValue.Type); } if (result.GetType() == typeof(DelegateType<>)) { var typeValue = (DelegateType)result; return Expression.Constant(typeValue.Value(), typeValue.Type); } return Expression.Constant(result); } return null; // throw new UnknownIdentifierException(identifier); } public Type GetType(string type) { object _type; if (TypeRegistry.TryGetValue(type, out _type)) { return (Type)_type; } return Type.GetType(type); } public ParameterList ParameterList = new ParameterList(); } }
// 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 OrInt32() { var test = new SimpleBinaryOpTest__OrInt32(); 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(); // 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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } 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__OrInt32 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int32); private const int Op2ElementCount = VectorSize / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static SimpleBinaryOpTest__OrInt32() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__OrInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.Or( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.Or( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.Or( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Sse2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__OrInt32(); var result = Sse2.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { if ((int)(left[0] | right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((int)(left[i] | right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Or)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
/* * Copyright 2002-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Globalization; using System.Reflection; using System.Runtime.Remoting; using Solenoid.Expressions.Support.Logging; using Solenoid.Expressions.Support.Reflection.Dynamic; namespace Solenoid.Expressions.Support.Util { /// <summary> /// Helper methods with regard to objects, types, properties, etc. /// </summary> /// <remarks> /// <p> /// Not intended to be used directly by applications. /// </p> /// </remarks> /// <author>Rod Johnson</author> /// <author>Juergen Hoeller</author> /// <author>Rick Evans (.NET)</author> public static class ObjectUtils { /// <summary> /// The <see cref="ILog" /> instance for this class. /// </summary> private static readonly ILog _log = LogManager.GetLogger(typeof (ObjectUtils)); /// <summary> /// An empty object array. /// </summary> public static readonly object[] EmptyObjects = {}; private static readonly MethodInfo _getHashCodeMethodInfo = null; static ObjectUtils() { var type = typeof (object); _getHashCodeMethodInfo = type.GetMethod("GetHashCode"); } /// <summary> /// Instantiates the type using the assembly specified to load the type. /// </summary> /// <remarks> /// This is a convenience in the case of needing to instantiate a type but not /// wanting to specify in the string the version, culture and public key token. /// </remarks> /// <param name="assembly">The assembly.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// If the <paramref name="assembly" /> or <paramref name="typeName" /> is <see langword="null" /> /// </exception> /// <exception cref="FatalReflectionException"> /// If cannot load the type from the assembly or the call to <code>InstantiateType(Type)</code> fails. /// </exception> public static object InstantiateType(Assembly assembly, string typeName) { AssertUtils.ArgumentNotNull(assembly, "assembly"); AssertUtils.ArgumentNotNull(typeName, "typeName"); var resolvedType = assembly.GetType(typeName, false, false); if (resolvedType == null) { throw new FatalReflectionException( string.Format( CultureInfo.InvariantCulture, "Cannot load type named [{0}] from assembly [{1}].", typeName, assembly)); } return InstantiateType(resolvedType); } /// <summary> /// Convenience method to instantiate a <see cref="System.Type" /> using /// its no-arg constructor. /// </summary> /// <remarks> /// <p> /// As this method doesn't try to instantiate <see cref="System.Type" />s /// by name, it should avoid <see cref="System.Type" /> loading issues. /// </p> /// </remarks> /// <param name="type"> /// The <see cref="System.Type" /> to instantiate* /// </param> /// <returns>A new instance of the <see cref="System.Type" />.</returns> /// <exception cref="System.ArgumentNullException"> /// If the <paramref name="type" /> is <see langword="null" /> /// </exception> /// <exception cref="FatalReflectionException"> /// If the <paramref name="type" /> is an abstract class, an interface, /// an open generic type or does not have a public no-argument constructor. /// </exception> public static object InstantiateType(Type type) { AssertUtils.ArgumentNotNull(type, "type"); var constructor = GetZeroArgConstructorInfo(type); return InstantiateType(constructor, EmptyObjects); } /// <summary> /// Gets the zero arg ConstructorInfo object, if the type offers such functionality. /// </summary> /// <param name="type">The type.</param> /// <returns>Zero argument ConstructorInfo</returns> /// <exception cref="FatalReflectionException"> /// If the type is an interface, abstract, open generic type, or does not have a zero-arg constructor. /// </exception> public static ConstructorInfo GetZeroArgConstructorInfo(Type type) { IsInstantiable(type); var constructor = type.GetConstructor(Type.EmptyTypes); if (constructor == null) { throw new FatalReflectionException( string.Format( CultureInfo.InvariantCulture, "Cannot instantiate a class that does not have a public no-argument constructor [{0}].", type)); } return constructor; } /// <summary> /// Determines whether the specified type is instantiable, i.e. not an interface, abstract class or contains /// open generic type parameters. /// </summary> /// <param name="type">The type.</param> public static void IsInstantiable(Type type) { if (type.IsInterface) { throw new FatalReflectionException( string.Format( CultureInfo.InvariantCulture, "Cannot instantiate an interface [{0}].", type)); } if (type.IsAbstract) { throw new FatalReflectionException( string.Format( CultureInfo.InvariantCulture, "Cannot instantiate an abstract class [{0}].", type)); } if (type.ContainsGenericParameters) { throw new FatalReflectionException( string.Format( CultureInfo.InvariantCulture, "Cannot instantiate an open generic type [{0}].", type)); } } /// <summary> /// Convenience method to instantiate a <see cref="System.Type" /> using /// the given constructor. /// </summary> /// <remarks> /// <p> /// As this method doesn't try to instantiate <see cref="System.Type" />s /// by name, it should avoid <see cref="System.Type" /> loading issues. /// </p> /// </remarks> /// <param name="constructor"> /// The constructor to use for the instantiation. /// </param> /// <param name="arguments"> /// The arguments to be passed to the constructor. /// </param> /// <returns>A new instance.</returns> /// <exception cref="System.ArgumentNullException"> /// If the <paramref name="constructor" /> is <see langword="null" /> /// </exception> /// <exception cref="FatalReflectionException"> /// If the <paramref name="constructor" />'s declaring type is an abstract class, /// an interface, an open generic type or does not have a public no-argument constructor. /// </exception> public static object InstantiateType(ConstructorInfo constructor, object[] arguments) { AssertUtils.ArgumentNotNull(constructor, "constructor"); if (_log.IsTraceEnabled) _log.Trace(string.Format("instantiating type [{0}] using constructor [{1}]", constructor.DeclaringType, constructor)); if (constructor.DeclaringType.IsInterface) { throw new FatalReflectionException( string.Format( CultureInfo.InvariantCulture, "Cannot instantiate an interface [{0}].", constructor.DeclaringType)); } if (constructor.DeclaringType.IsAbstract) { throw new FatalReflectionException( string.Format( CultureInfo.InvariantCulture, "Cannot instantiate an abstract class [{0}].", constructor.DeclaringType)); } if (constructor.DeclaringType.ContainsGenericParameters) { throw new FatalReflectionException( string.Format( CultureInfo.InvariantCulture, "Cannot instantiate an open generic type [{0}].", constructor.DeclaringType)); } try { // replaced with SafeConstructor() to avoid nasty "TargetInvocationException"s in NET >= 2.0 return (new SafeConstructor(constructor)).Invoke(arguments); } catch (Exception ex) { var ctorType = constructor.DeclaringType; throw new FatalReflectionException( string.Format( CultureInfo.InvariantCulture, "Cannot instantiate Type [{0}] using ctor [{1}] : '{2}'", constructor.DeclaringType, constructor, ex.Message), ex); } } /// <summary> /// Checks whether the supplied <paramref name="instance" /> is not a transparent proxy and is /// assignable to the supplied <paramref name="type" />. /// </summary> /// <remarks> /// <p> /// Neccessary when dealing with server-activated remote objects, because the /// object is of the type TransparentProxy and regular <c>is</c> testing for assignable /// types does not work. /// </p> /// <p> /// Transparent proxy instances always return <see langword="true" /> when tested /// with the <c>'is'</c> operator (C#). This method only checks if the object /// is assignable to the type if it is not a transparent proxy. /// </p> /// </remarks> /// <param name="type">The target <see cref="System.Type" /> to be checked.</param> /// <param name="instance">The value that should be assigned to the type.</param> /// <returns> /// <see langword="true" /> if the supplied <paramref name="instance" /> is not a /// transparent proxy and is assignable to the supplied <paramref name="type" />. /// </returns> public static bool IsAssignableAndNotTransparentProxy(Type type, object instance) { if (!RemotingServices.IsTransparentProxy(instance)) { return IsAssignable(type, instance); } return false; } /// <summary> /// Determine if the given <see cref="System.Type" /> is assignable from the /// given value, assuming setting by reflection and taking care of transparent proxies. /// </summary> /// <remarks> /// <p> /// Considers primitive wrapper classes as assignable to the /// corresponding primitive types. /// </p> /// <p> /// For example used in an object factory's constructor resolution. /// </p> /// </remarks> /// <param name="type">The target <see cref="System.Type" />.</param> /// <param name="obj">The value that should be assigned to the type.</param> /// <returns>True if the type is assignable from the value.</returns> public static bool IsAssignable(Type type, object obj) { AssertUtils.ArgumentNotNull(type, "type"); if (!type.IsPrimitive && obj == null) { return true; } if (RemotingServices.IsTransparentProxy(obj)) { var rp = RemotingServices.GetRealProxy(obj); if (rp is IRemotingTypeInfo) { return ((IRemotingTypeInfo) rp).CanCastTo(type, obj); } if (rp != null) { type = rp.GetProxiedType(); } if (type == null) { // cannot decide return false; } } return (type.IsInstanceOfType(obj) || (type.Equals(typeof (bool)) && obj is Boolean) || (type.Equals(typeof (byte)) && obj is Byte) || (type.Equals(typeof (char)) && obj is Char) || (type.Equals(typeof (sbyte)) && obj is SByte) || (type.Equals(typeof (int)) && obj is Int32) || (type.Equals(typeof (short)) && obj is Int16) || (type.Equals(typeof (long)) && obj is Int64) || (type.Equals(typeof (float)) && obj is Single) || (type.Equals(typeof (double)) && obj is Double)); } /// <summary> /// Check if the given <see cref="System.Type" /> represents a /// "simple" property, /// i.e. a primitive, a <see cref="System.String" />, a /// <see cref="System.Type" />, or a corresponding array. /// </summary> /// <remarks> /// <p> /// Used to determine properties to check for a "simple" dependency-check. /// </p> /// </remarks> /// <param name="type"> /// The <see cref="System.Type" /> to check. /// </param> public static bool IsSimpleProperty(Type type) { return type.IsPrimitive || type == typeof (string) || type == typeof (string[]) || IsPrimitiveArray(type) || type == typeof (Type) || type == typeof (Type[]); } /// <summary> /// Check if the given class represents a primitive array, /// i.e. boolean, byte, char, short, int, long, float, or double. /// </summary> public static bool IsPrimitiveArray(Type type) { return typeof (bool[]) == type || typeof (sbyte[]) == type || typeof (char[]) == type || typeof (short[]) == type || typeof (int[]) == type || typeof (long[]) == type || typeof (float[]) == type || typeof (double[]) == type; } /// <summary> /// Determines whether the specified array is null or empty. /// </summary> /// <param name="array">The array to check.</param> /// <returns> /// <c>true</c> if the specified array is null empty; otherwise, <c>false</c>. /// </returns> public static bool IsEmpty(object[] array) { return (array == null || array.Length == 0); } /// <summary> /// Determine if the given objects are equal, returning <see langword="true" /> /// if both are <see langword="null" /> respectively <see langword="false" /> /// if only one is <see langword="null" />. /// </summary> /// <param name="o1">The first object to compare.</param> /// <param name="o2">The second object to compare.</param> /// <returns> /// <see langword="true" /> if the given objects are equal. /// </returns> public static bool NullSafeEquals(object o1, object o2) { return (o1 == o2 || (o1 != null && o1.Equals(o2))); } /// <summary> /// Return as hash code for the given object; typically the value of /// <code>{@link Object#hashCode()}</code>. If the object is an array, /// this method will delegate to any of the <code>nullSafeHashCode</code> /// methods for arrays in this class. If the object is <code>null</code>, /// this method returns 0. /// </summary> public static int NullSafeHashCode(object o1) { return (o1 != null ? o1.GetHashCode() : 0); } /// <summary> /// Returns the first element in the supplied <paramref name="enumerator" />. /// </summary> /// <param name="enumerator"> /// The <see cref="System.Collections.IEnumerator" /> to use to enumerate /// elements. /// </param> /// <returns> /// The first element in the supplied <paramref name="enumerator" />. /// </returns> /// <exception cref="System.IndexOutOfRangeException"> /// If the supplied <paramref name="enumerator" /> did not have any elements. /// </exception> public static object EnumerateFirstElement(IEnumerator enumerator) { return EnumerateElementAtIndex(enumerator, 0); } /// <summary> /// Returns the first element in the supplied <paramref name="enumerable" />. /// </summary> /// <param name="enumerable"> /// The <see cref="System.Collections.IEnumerable" /> to use to enumerate /// elements. /// </param> /// <returns> /// The first element in the supplied <paramref name="enumerable" />. /// </returns> /// <exception cref="System.IndexOutOfRangeException"> /// If the supplied <paramref name="enumerable" /> did not have any elements. /// </exception> /// <exception cref="System.ArgumentNullException"> /// If the supplied <paramref name="enumerable" /> is <see langword="null" />. /// </exception> public static object EnumerateFirstElement(IEnumerable enumerable) { AssertUtils.ArgumentNotNull(enumerable, "enumerable"); return EnumerateElementAtIndex(enumerable.GetEnumerator(), 0); } /// <summary> /// Returns the element at the specified index using the supplied /// <paramref name="enumerator" />. /// </summary> /// <param name="enumerator"> /// The <see cref="System.Collections.IEnumerator" /> to use to enumerate /// elements until the supplied <paramref name="index" /> is reached. /// </param> /// <param name="index"> /// The index of the element in the enumeration to return. /// </param> /// <returns> /// The element at the specified index using the supplied /// <paramref name="enumerator" />. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// If the supplied <paramref name="index" /> was less than zero, or the /// supplied <paramref name="enumerator" /> did not contain enough elements /// to be able to reach the supplied <paramref name="index" />. /// </exception> public static object EnumerateElementAtIndex(IEnumerator enumerator, int index) { if (index < 0) { throw new ArgumentOutOfRangeException(); } object element = null; var i = 0; while (enumerator.MoveNext()) { element = enumerator.Current; if (++i > index) { break; } } if (i < index) { throw new ArgumentOutOfRangeException(); } return element; } /// <summary> /// Returns the element at the specified index using the supplied /// <paramref name="enumerable" />. /// </summary> /// <param name="enumerable"> /// The <see cref="System.Collections.IEnumerable" /> to use to enumerate /// elements until the supplied <paramref name="index" /> is reached. /// </param> /// <param name="index"> /// The index of the element in the enumeration to return. /// </param> /// <returns> /// The element at the specified index using the supplied /// <paramref name="enumerable" />. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// If the supplied <paramref name="index" /> was less than zero, or the /// supplied <paramref name="enumerable" /> did not contain enough elements /// to be able to reach the supplied <paramref name="index" />. /// </exception> /// <exception cref="System.ArgumentNullException"> /// If the supplied <paramref name="enumerable" /> is <see langword="null" />. /// </exception> public static object EnumerateElementAtIndex(IEnumerable enumerable, int index) { AssertUtils.ArgumentNotNull(enumerable, "enumerable"); return EnumerateElementAtIndex(enumerable.GetEnumerator(), index); } /// <summary> /// Gets the qualified name of the given method, consisting of /// fully qualified interface/class name + "." method name. /// </summary> /// <param name="method">The method.</param> /// <returns>qualified name of the method.</returns> public static string GetQualifiedMethodName(MethodInfo method) { AssertUtils.ArgumentNotNull(method, "method", "MethodInfo must not be null"); return method.DeclaringType.FullName + "." + method.Name; } /// <summary> /// Return a String representation of an object's overall identity. /// </summary> /// <param name="obj">The object (may be <code>null</code>).</param> /// <returns> /// The object's identity as String representation, /// or an empty String if the object was <code>null</code> /// </returns> public static object IdentityToString(object obj) { if (obj == null) { return string.Empty; } return obj.GetType().FullName + "@" + GetIdentityHexString(obj); } /// <summary> /// Gets a hex String form of an object's identity hash code. /// </summary> /// <param name="obj">The obj.</param> /// <returns>The object's identity code in hex notation</returns> public static string GetIdentityHexString(object obj) { var hashcode = (int) _getHashCodeMethodInfo.Invoke(obj, null); return hashcode.ToString("X6"); } } }
using System; using Eto.Forms; using System.Linq.Expressions; namespace Eto.Forms { /// <summary> /// Binding for a particular object to get/set values from/to /// </summary> /// <remarks> /// This binding provides a way to get/set values for a particular object. This uses /// a <see cref="IndirectBinding{T}"/> as its logic to actually retrieve/set the values. /// /// This acts as a bridge between the <see cref="IndirectBinding{T}"/> and <see cref="DirectBinding{T}"/> /// so that you can utilize the <see cref="DirectBinding{T}.DataValueChanged"/> method. /// /// Typically, one would use the <see cref="PropertyBinding{T}"/>, or the <see cref="C:ObjectBinding{T,TValue}(T, string)"/> /// constructor to hook up this binding to a particular property of the specified object /// </remarks> /// <typeparam name="TValue">The type of value for the binding.</typeparam> public class ObjectBinding<TValue> : ObjectBinding<object, TValue> { /// <summary> /// Initializes a new instance of the ObjectBinding with the specified object and binding to get/set values with /// </summary> /// <param name="dataItem">object to get/set values from</param> /// <param name="innerBinding">binding to use to get/set the values from the dataItem</param> public ObjectBinding(object dataItem, IndirectBinding<TValue> innerBinding) : base(dataItem, innerBinding) { } /// <summary> /// Initializes a new instance of the ObjectBinding with the specified object and property for a <see cref="PropertyBinding{T}"/> /// </summary> /// <remarks> /// This is a shortcut to set up the binding to get/set values from a particular property of the specified object /// </remarks> /// <param name="dataItem">object to get/set values from</param> /// <param name="property">property of the dataItem to get/set values</param> public ObjectBinding(object dataItem, string property) : base(dataItem, property) { } } /// <summary> /// Binding for a particular object to get/set values from/to /// </summary> /// <remarks> /// This binding provides a way to get/set values for a particular object. This uses /// a <see cref="IndirectBinding{T}"/> as its logic to actually retrieve/set the values. /// /// This acts as a bridge between the <see cref="IndirectBinding{T}"/> and <see cref="DirectBinding{T}"/> /// so that you can utilize the <see cref="DirectBinding{T}.DataValueChanged"/> method. /// /// Typically, one would use the <see cref="PropertyBinding{T}"/>, or the <see cref="C:ObjectBinding{T,TValue}(T, string)"/> /// constructor to hook up this binding to a particular property of the specified object /// </remarks> /// <typeparam name="T">The type of object to bind to.</typeparam> /// <typeparam name="TValue">The type of value for the binding.</typeparam> /// <copyright>(c) 2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class ObjectBinding<T, TValue> : DirectBinding<TValue> { object dataValueChangedReference; T dataItem; /// <summary> /// Gets the binding used to get/set the values from the <see cref="DataItem"/> /// </summary> public IndirectBinding<TValue> InnerBinding { get; private set; } /// <summary> /// Gets the object to get/set the values using the <see cref="InnerBinding"/> /// </summary> public T DataItem { get { return dataItem; } set { var updateEvent = dataValueChangedReference != null; if (updateEvent) RemoveEvent(DataValueChangedEvent); dataItem = value; OnDataValueChanged(EventArgs.Empty); if (updateEvent) HandleEvent(DataValueChangedEvent); } } /// <summary> /// Gets or sets the default value to use when setting the value for this binding when input value is null /// </summary> public TValue SettingNullValue { get; set; } /// <summary> /// Gets or sets the default value to use when getting the value for this binding when the <see cref="DataItem"/> or property value is null /// </summary> public TValue GettingNullValue { get; set; } /// <summary> /// Initializes a new instance of the <see cref="ObjectBinding{T,TValue}"/> class. /// </summary> /// <param name="dataItem">Data item to get/set the values from/to.</param> /// <param name="getValue">Delegate to get the value from the object.</param> /// <param name="setValue">Delegate to set the value to the object.</param> /// <param name="addChangeEvent">Delegate to add the change event.</param> /// <param name="removeChangeEvent">Delegate to remove the chang event.</param> public ObjectBinding(T dataItem, Func<T, TValue> getValue, Action<T, TValue> setValue = null, Action<T, EventHandler<EventArgs>> addChangeEvent = null, Action<T, EventHandler<EventArgs>> removeChangeEvent = null) : this(dataItem, new DelegateBinding<T, TValue>(getValue, setValue, addChangeEvent, removeChangeEvent)) { } /// <summary> /// Initializes a new instance of the ObjectBinding with the specified object and property for a <see cref="PropertyBinding{T}"/> /// </summary> /// <remarks> /// This is a shortcut to set up the binding to get/set values from a particular property of the specified object /// </remarks> /// <param name="dataItem">object to get/set values from</param> /// <param name="property">property of the dataItem to get/set values</param> public ObjectBinding(T dataItem, string property) : this(dataItem, new PropertyBinding<TValue>(property)) { } /// <summary> /// Initializes a new instance of the ObjectBinding with the specified object and binding to get/set values with /// </summary> /// <param name="dataItem">object to get/set values from</param> /// <param name="innerBinding">binding to use to get/set the values from the dataItem</param> public ObjectBinding(T dataItem, IndirectBinding<TValue> innerBinding) { this.dataItem = dataItem; InnerBinding = innerBinding; InnerBinding.Changed += HandleInnerBindingChanged; InnerBinding.Changing += HandleInnerBindingChanging; } void HandleInnerBindingChanging(object sender, BindingChangingEventArgs e) { OnChanging(e); } void HandleInnerBindingChanged(object sender, BindingChangedEventArgs e) { OnChanged(e); } /// <summary> /// Gets or sets the value of this binding on the bound object /// </summary> /// <remarks> /// This uses the <see cref="InnerBinding"/> on the <see cref="DataItem"/> to get/set the value /// </remarks> public override TValue DataValue { get { var val = InnerBinding.GetValue(DataItem); return Equals(val, default(T)) ? GettingNullValue : val; } set { InnerBinding.SetValue(DataItem, Equals(value, default(T)) ? SettingNullValue : value); } } /// <summary> /// Hooks up the late bound events for this object /// </summary> protected override void HandleEvent(string id) { switch (id) { case DataValueChangedEvent: if (dataValueChangedReference == null) dataValueChangedReference = InnerBinding.AddValueChangedHandler( DataItem, new EventHandler<EventArgs>(HandleChangedEvent) ); break; default: base.HandleEvent(id); break; } } /// <summary> /// Removes the late bound events for this object /// </summary> protected override void RemoveEvent(string id) { switch (id) { case DataValueChangedEvent: if (dataValueChangedReference != null) { InnerBinding.RemoveValueChangedHandler( dataValueChangedReference, new EventHandler<EventArgs>(HandleChangedEvent) ); dataValueChangedReference = null; } break; default: base.RemoveEvent(id); break; } } /// <summary> /// Unbinds this binding /// </summary> public override void Unbind() { base.Unbind(); RemoveEvent(DataValueChangedEvent); InnerBinding.Unbind(); } void HandleChangedEvent(object sender, EventArgs e) { OnDataValueChanged(e); } /// <summary> /// Creates a new dual binding between the specified <paramref name="sourceBinding"/> and this binding. /// </summary> /// <remarks> /// This creates a <see cref="DualBinding{TValue}"/> between the specified <paramref name="sourceBinding"/> and this binding. /// You must keep a reference to the binding to unbind when finished. /// </remarks> /// <param name="sourceBinding">Source binding to bind from.</param> /// <param name="mode">Dual binding mode.</param> public virtual DualBinding<TValue> Bind(DirectBinding<TValue> sourceBinding, DualBindingMode mode = DualBindingMode.TwoWay) { return new DualBinding<TValue>(sourceBinding, this, mode); } /// <summary> /// Creates a new dual binding using a <see cref="DelegateBinding{TValue}"/> with the specified delegates and this binding. /// </summary> /// <remarks> /// This creates a <see cref="DualBinding{TValue}"/> between a new <see cref="DelegateBinding{TValue}"/> and this binding. /// This does not require an object instance for the delegates to get/set the value. /// You must keep a reference to the binding to unbind when finished. /// </remarks> /// <param name="getValue">Delegate to get the value.</param> /// <param name="setValue">Delegate to set the value when changed.</param> /// <param name="addChangeEvent">Delegate to add a change event when the value changes.</param> /// <param name="removeChangeEvent">Delegate to remove the change event.</param> /// <param name="mode">Dual binding mode.</param> public DualBinding<TValue> Bind(Func<TValue> getValue, Action<TValue> setValue = null, Action<EventHandler<EventArgs>> addChangeEvent = null, Action<EventHandler<EventArgs>> removeChangeEvent = null, DualBindingMode mode = DualBindingMode.TwoWay) { return Bind(new DelegateBinding<TValue> { GetValue = getValue, SetValue = setValue, AddChangeEvent = addChangeEvent, RemoveChangeEvent = removeChangeEvent }, mode); } /// <summary> /// Creates a new dual binding between the specified <paramref name="objectBinding"/> and this binding. /// </summary> /// <param name="objectValue">Object to get/set the values from/to.</param> /// <param name="objectBinding">Indirect binding to get/set the values from the <paramref name="objectValue"/>.</param> /// <param name="mode">Dual binding mode.</param> /// <typeparam name="TObject">The type of the object that is being bound to.</typeparam> public DualBinding<TValue> Bind<TObject>(TObject objectValue, IndirectBinding<TValue> objectBinding, DualBindingMode mode = DualBindingMode.TwoWay) { var valueBinding = new ObjectBinding<TObject, TValue>(objectValue, objectBinding); return Bind(sourceBinding: valueBinding, mode: mode); } /// <summary> /// Creates a binding to the <paramref name="propertyName"/> of the specified <paramref name="objectValue"/>. /// </summary> /// <remarks> /// This is a shortcut to using the <see cref="PropertyBinding{TValue}"/>. /// This has the advantage of registering automatically to <see cref="System.ComponentModel.INotifyPropertyChanged"/> /// or to an event named after the property with a "Changed" suffix. /// </remarks> /// <param name="objectValue">Object to bind to.</param> /// <param name="propertyName">Name of the property to bind to on the <paramref name="objectValue"/>.</param> /// <param name="mode">Direction of the binding.</param> public DualBinding<TValue> Bind(object objectValue, string propertyName, DualBindingMode mode = DualBindingMode.TwoWay) { return Bind<object>(objectValue, new PropertyBinding<TValue>(propertyName), mode: mode); } /// <summary> /// Creates a binding to the specified <paramref name="objectValue"/> with the specified <paramref name="propertyExpression"/>. /// </summary> /// <remarks> /// This has the advantage of registering automatically to <see cref="System.ComponentModel.INotifyPropertyChanged"/> /// or to an event named after the property with a "Changed" suffix, if the expression is a property. /// When the expression does not evaluate to a property, it will not be able to bind to the changed events and will /// use the expression as a delegate directly. /// </remarks> /// <typeparam name="TObject">Type of the data context to bind to</typeparam> /// <param name="objectValue">Object to bind to.</param> /// <param name="propertyExpression">Expression for a property of the <paramref name="objectValue"/>, or a non-property expression with no change event binding.</param> /// <param name="mode">Direction of the binding</param> /// <returns>The binding between the data context and this binding</returns> public DualBinding<TValue> Bind<TObject>(TObject objectValue, Expression<Func<TObject, TValue>> propertyExpression, DualBindingMode mode = DualBindingMode.TwoWay) { var memberInfo = propertyExpression.GetMemberInfo(); if (memberInfo == null) { var getValue = propertyExpression.Compile(); return Bind(() => getValue(objectValue), null, null, null, mode); } return Bind(objectValue, new PropertyBinding<TValue>(memberInfo.Member.Name), mode); } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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.Linq; using System.Abstract; using System.Collections.Generic; using Castle.Windsor; using Castle.MicroKernel.Registration; using System.Reflection; using Castle.Core; namespace Contoso.Abstract { /// <summary> /// ICastleWindsorServiceRegistrar /// </summary> public interface ICastleWindsorServiceRegistrar : IServiceRegistrar { //void RegisterAll<Source>(); } /// <summary> /// CastleWindsorServiceRegistrar /// </summary> public class CastleWindsorServiceRegistrar : ICastleWindsorServiceRegistrar, IDisposable, ICloneable, IServiceRegistrarBehaviorAccessor { private CastleWindsorServiceLocator _parent; private IWindsorContainer _container; /// <summary> /// Initializes a new instance of the <see cref="CastleWindsorServiceRegistrar"/> class. /// </summary> /// <param name="parent">The parent.</param> /// <param name="container">The container.</param> public CastleWindsorServiceRegistrar(CastleWindsorServiceLocator parent, IWindsorContainer container) { _parent = parent; _container = container; LifetimeForRegisters = ServiceRegistrarLifetime.Transient; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { } object ICloneable.Clone() { return MemberwiseClone(); } // locator /// <summary> /// Gets the locator. /// </summary> public IServiceLocator Locator { get { return _parent; } } // enumerate /// <summary> /// Determines whether this instance has registered. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <returns> /// <c>true</c> if this instance has registered; otherwise, <c>false</c>. /// </returns> public bool HasRegistered<TService>() { return HasRegistered(typeof(TService)); } /// <summary> /// Determines whether the specified service type has registered. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <returns> /// <c>true</c> if the specified service type has registered; otherwise, <c>false</c>. /// </returns> public bool HasRegistered(Type serviceType) { return _container.Kernel.HasComponent(serviceType); } /// <summary> /// Gets the registrations for. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <returns></returns> public IEnumerable<ServiceRegistration> GetRegistrationsFor(Type serviceType) { return _container.Kernel.GetAssignableHandlers(serviceType) .Select(x => new ServiceRegistration { ImplementationType = x.ComponentModel.Implementation }); } /// <summary> /// Gets the registrations. /// </summary> public IEnumerable<ServiceRegistration> Registrations { get { return _container.Kernel.GetAssignableHandlers(typeof(object)) .Select(x => new ServiceRegistration { ImplementationType = x.ComponentModel.Implementation }); } } // register type /// <summary> /// Gets the lifetime for registers. /// </summary> public ServiceRegistrarLifetime LifetimeForRegisters { get; private set; } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> public void Register(Type serviceType) { _container.Register(Component.For(serviceType).LifeStyle.Is(GetLifetime())); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="name">The name.</param> public void Register(Type serviceType, string name) { _container.Register(Component.For(serviceType).Named(name).LifeStyle.Is(GetLifetime())); } // register implementation /// <summary> /// Registers this instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="TImplementation">The type of the implementation.</typeparam> public void Register<TService, TImplementation>() where TService : class where TImplementation : class, TService { EnsureTransientLifestyle(); _container.Register(Component.For<TService>().ImplementedBy<TImplementation>().LifeStyle.Is(GetLifetime())); } /// <summary> /// Registers the specified name. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="TImplementation">The type of the implementation.</typeparam> /// <param name="name">The name.</param> public void Register<TService, TImplementation>(string name) where TService : class where TImplementation : class, TService { EnsureTransientLifestyle(); _container.Register(Component.For<TService>().Named(name).ImplementedBy<TImplementation>().LifeStyle.Is(GetLifetime())); } /// <summary> /// Registers the specified implementation type. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="implementationType">Type of the implementation.</param> public void Register<TService>(Type implementationType) where TService : class { EnsureTransientLifestyle(); _container.Register(Component.For<TService>().ImplementedBy(implementationType).LifeStyle.Is(GetLifetime())); } /// <summary> /// Registers the specified implementation type. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="implementationType">Type of the implementation.</param> /// <param name="name">The name.</param> public void Register<TService>(Type implementationType, string name) where TService : class { EnsureTransientLifestyle(); _container.Register(Component.For<TService>().Named(name).ImplementedBy(implementationType).LifeStyle.Is(GetLifetime())); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="implementationType">Type of the implementation.</param> public void Register(Type serviceType, Type implementationType) { EnsureTransientLifestyle(); _container.Register(Component.For(serviceType).ImplementedBy(implementationType).LifeStyle.Is(GetLifetime())); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="implementationType">Type of the implementation.</param> /// <param name="name">The name.</param> public void Register(Type serviceType, Type implementationType, string name) { EnsureTransientLifestyle(); _container.Register(Component.For(serviceType).Named(name).ImplementedBy(implementationType).LifeStyle.Is(GetLifetime())); } // register instance /// <summary> /// Registers the instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="instance">The instance.</param> public void RegisterInstance<TService>(TService instance) where TService : class { _container.Register(Component.For<TService>().Instance(instance)); } /// <summary> /// Registers the instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="instance">The instance.</param> /// <param name="name">The name.</param> public void RegisterInstance<TService>(TService instance, string name) where TService : class { _container.Register(Component.For<TService>().Named(name).Instance(instance)); } /// <summary> /// Registers the instance. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="instance">The instance.</param> public void RegisterInstance(Type serviceType, object instance) { _container.Register(Component.For(serviceType).Instance(instance)); } /// <summary> /// Registers the instance. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="instance">The instance.</param> /// <param name="name">The name.</param> public void RegisterInstance(Type serviceType, object instance, string name) { _container.Register(Component.For(serviceType).Named(name).Instance(instance)); } // register method /// <summary> /// Registers the specified factory method. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="factoryMethod">The factory method.</param> public void Register<TService>(Func<IServiceLocator, TService> factoryMethod) where TService : class { _container.Register(Component.For<TService>().UsingFactoryMethod<TService>(x => factoryMethod(_parent)).LifeStyle.Is(GetLifetime())); } /// <summary> /// Registers the specified factory method. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="factoryMethod">The factory method.</param> /// <param name="name">The name.</param> public void Register<TService>(Func<IServiceLocator, TService> factoryMethod, string name) where TService : class { _container.Register(Component.For<TService>().UsingFactoryMethod<TService>(x => factoryMethod(_parent)).Named(name).LifeStyle.Is(GetLifetime())); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="factoryMethod">The factory method.</param> public void Register(Type serviceType, Func<IServiceLocator, object> factoryMethod) { _container.Register(Component.For(serviceType).UsingFactoryMethod(x => factoryMethod(_parent)).LifeStyle.Is(GetLifetime())); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="factoryMethod">The factory method.</param> /// <param name="name">The name.</param> public void Register(Type serviceType, Func<IServiceLocator, object> factoryMethod, string name) { _container.Register(Component.For(serviceType).UsingFactoryMethod(x => factoryMethod(_parent)).Named(name).LifeStyle.Is(GetLifetime())); } // interceptor /// <summary> /// Registers the interceptor. /// </summary> /// <param name="interceptor">The interceptor.</param> public void RegisterInterceptor(IServiceLocatorInterceptor interceptor) { _container.Kernel.ComponentModelCreated += model => { if (interceptor.Match(model.Implementation)) interceptor.ItemCreated(model.Implementation, model.LifestyleType == LifestyleType.Transient); }; } #region Domain specific //public void RegisterAll<TService>() { AllTypes.Of<TService>(); } //private static string MakeId(Type serviceType, Type implementationType) { return serviceType.Name + "->" + implementationType.FullName; } #endregion #region Behavior bool IServiceRegistrarBehaviorAccessor.RegisterInLocator { get { return true; } } ServiceRegistrarLifetime IServiceRegistrarBehaviorAccessor.Lifetime { get { return LifetimeForRegisters; } set { LifetimeForRegisters = value; } } #endregion private void EnsureTransientLifestyle() { if (LifetimeForRegisters != ServiceRegistrarLifetime.Transient) throw new NotSupportedException(); } private LifestyleType GetLifetime() { switch (LifetimeForRegisters) { case ServiceRegistrarLifetime.Transient: return LifestyleType.Transient; case ServiceRegistrarLifetime.Singleton: return LifestyleType.Singleton; case ServiceRegistrarLifetime.Thread: return LifestyleType.Thread; case ServiceRegistrarLifetime.Pooled: return LifestyleType.Pooled; case ServiceRegistrarLifetime.Request: return LifestyleType.PerWebRequest; default: throw new NotSupportedException(); } } } }
using System; using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting; using Untech.SharePoint.Common.CodeAnnotations; using Untech.SharePoint.Common.Configuration; using Untech.SharePoint.Common.Data; using Untech.SharePoint.Common.Mappings; using Untech.SharePoint.Common.Mappings.Annotation; using Untech.SharePoint.Common.MetaModels; namespace Untech.SharePoint.Common.Test.Mappings.Annotation { [TestClass] [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")] public class AnnotatedFieldPartTest { [TestMethod] public void CanDefineFieldAnnotation() { var ct = GetContentType<Entity>(); Assert.AreEqual(2, ct.Fields.Count); Assert.AreEqual("OriginalName", ct.Fields["Field1"].InternalName); Assert.AreEqual("Field2", ct.Fields["Field2"].InternalName); } [TestMethod] public void CanInheritFieldAnnotation() { var ct = GetContentType<InheritedAnnotation>(); Assert.AreEqual(2, ct.Fields.Count); Assert.AreEqual("OriginalName", ct.Fields["Field1"].InternalName); Assert.AreEqual("Field2", ct.Fields["Field2"].InternalName); } [TestMethod] public void CanOverwriteFieldAnnotation() { var ct = GetContentType<OverwrittenAnnotation>(); Assert.AreEqual(2, ct.Fields.Count); Assert.AreEqual("NewName", ct.Fields["Field1"].InternalName); Assert.AreEqual("Field2", ct.Fields["Field2"].InternalName); } [TestMethod] public void CanRemoveParentField() { var ct = GetContentType<RemovedField>(); Assert.AreEqual(1, ct.Fields.Count); Assert.AreEqual("OriginalName", ct.Fields["Field1"].InternalName); } [TestMethod] public void CanRemoveThatField() { var ct = GetContentType<AddedAndRemovedField>(); Assert.AreEqual(2, ct.Fields.Count); Assert.AreEqual("OriginalName", ct.Fields["Field1"].InternalName); Assert.AreEqual("Field2", ct.Fields["Field2"].InternalName); } [TestMethod] public void CanIgnoreConstantFields() { var ct = GetContentType<ConstField>(); Assert.AreEqual(2, ct.Fields.Count); Assert.AreEqual("OriginalName", ct.Fields["Field1"].InternalName); Assert.AreEqual("Field2", ct.Fields["Field2"].InternalName); } [TestMethod] public void CanIgnoreStaticProperties() { var ct = GetContentType<StaticProperty>(); Assert.AreEqual(2, ct.Fields.Count); Assert.AreEqual("OriginalName", ct.Fields["Field1"].InternalName); Assert.AreEqual("Field2", ct.Fields["Field2"].InternalName); } [TestMethod] public void ThrowIfFieldIsReadOnly() { CustomAssert.Throw<InvalidAnnotationException>(() => { GetContentType<ReadOnlyField>(); }); } [TestMethod] public void ThrowIfPropertyIsReadOnly() { CustomAssert.Throw<InvalidAnnotationException>(() => { GetContentType<ReadOnlyProperty>(); }); } [TestMethod] public void CanUsePrivateSetter() { var ct = GetContentType<PrivateSetter>(); Assert.AreEqual(3, ct.Fields.Count); Assert.AreEqual("OriginalName", ct.Fields["Field1"].InternalName); Assert.AreEqual("Field2", ct.Fields["Field2"].InternalName); Assert.AreEqual("Field3", ct.Fields["Field3"].InternalName); } [TestMethod] public void ThrowIfPropertyIsWriteOnly() { CustomAssert.Throw<InvalidAnnotationException>(() => { GetContentType<WriteOnlyProperty>(); }); } [TestMethod] public void ThrowIfIndexer() { CustomAssert.Throw<InvalidAnnotationException>(() => { GetContentType<Indexer>(); }); } private MetaContentType GetContentType<T>() { var metaContext = new AnnotatedContextMapping<Ctx<T>>().GetMetaContext(); return metaContext.Lists["List"].ContentTypes[typeof (T)]; } #region [Nested Classes] public class Ctx<T> : ISpContext { [SpList("List")] public ISpList<T> List { get; set; } public Config Config { get; private set; } public IMappingSource MappingSource { get; private set; } public MetaContext Model { get; private set; } } [UsedImplicitly(ImplicitUseTargetFlags.WithMembers)] public class Entity { [SpField(Name = "OriginalName")] public virtual string Field1 { get; set; } [SpField] public virtual string Field2 { get; set; } public string NotAnnotatedField { get; set; } } public class InheritedAnnotation : Entity { public override string Field1 { get; set; } } public class OverwrittenAnnotation : Entity { [SpField(Name = "NewName")] public override string Field1 { get; set; } } public class RemovedField : Entity { [SpFieldRemoved] public override string Field2 { get; set; } } public class AddedAndRemovedField : Entity { [SpField] [SpFieldRemoved] public string Field3 { get; set; } } public class ReadOnlyProperty : Entity { [SpField] public string Field3 { get { throw new NotImplementedException(); } } } public class PrivateSetter : Entity { [SpField] public string Field3 { get; private set; } } public class WriteOnlyProperty : Entity { [SpField] public string Field3 { set { throw new NotImplementedException(); } } } public class ReadOnlyField : Entity { [SpField] public readonly string Field3 = "Test"; } public class ConstField : Entity { [SpField] public const string Field3 = null; } public class StaticProperty: Entity { [SpField] public static string Field3 { get; set; } } public class Indexer : Entity { [SpField] public string this[string key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } #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; using System.Collections.Generic; using System.Text; using System.Xml; using System.IO; using System.Runtime.Remoting; using System.Globalization; using System.Reflection; using System.CodeDom; using System.CodeDom.Compiler; using System.Xaml; using Microsoft.CSharp; using Microsoft.Build.Evaluation; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.Build.Shared; using Microsoft.Build.Tasks.Xaml; using Xunit; namespace Microsoft.Build.UnitTests.XamlDataDrivenToolTask_Tests { /// <summary> /// Test fixture for testing the DataDrivenToolTask class with a fake task generated by XamlTestHelpers.cs /// Tests to see if certain switches are appended. /// </summary> public class GeneratedTask { private Assembly _fakeTaskDll; public GeneratedTask() { _fakeTaskDll = XamlTestHelpers.SetupGeneratedCode(); } /// <summary> /// Test to see whether all of the correct boolean switches are appended. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestDefaultFlags() { object fakeTaskInstance = CreateFakeTask(); CheckCommandLine("/always /Cr:CT", XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); } /// <summary> /// A test to see if all of the reversible flags are generated correctly /// This test case leaves the default flags the way they are /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestReversibleFlagsWithDefaults() { object fakeTaskInstance = CreateFakeTask(); XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicReversible", true); string expectedResult = "/always /Br /Cr:CT"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); } /// <summary> /// A test to see if all of the reversible flags are generated correctly /// This test case explicitly sets the ComplexReversible to be false /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestReversibleFlagsWithoutDefaults() { object fakeTaskInstance = CreateFakeTask(); XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicReversible", true); XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexReversible", false); string expectedResult = "/always /Br /Cr:CF"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); } /// <summary> /// Tests to make sure enums are working well. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestBasicString() { object fakeTaskInstance = CreateFakeTask(); XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicString", "Enum1"); string expectedResult = "/always /Bs1 /Cr:CT"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); } [Fact] [Trait("Category", "mono-osx-failing")] public void TestDynamicEnum() { object fakeTaskInstance = CreateFakeTask(); XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicDynamicEnum", "MyBeforeTarget"); string expectedResult = "/always MyBeforeTarget /Cr:CT"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); } /// <summary> /// Tests the basic string array type /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestBasicStringArray() { object fakeTaskInstance = CreateFakeTask(); string[] fakeArray = new string[1]; fakeArray[0] = "FakeStringArray"; XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicStringArray", new object[] { fakeArray }); string expectedResult = "/always /BsaFakeStringArray /Cr:CT"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); } /// <summary> /// Tests the basic string array type, with an array that contains multiple values. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestBasicStringArray_MultipleValues() { object fakeTaskInstance = CreateFakeTask(); string[] fakeArray = new string[3]; fakeArray[0] = "Fake"; fakeArray[1] = "String"; fakeArray[2] = "Array"; XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicStringArray", new object[] { fakeArray }); string expectedResult = "/always /BsaFake /BsaString /BsaArray /Cr:CT"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); } /// <summary> /// Tests to see whether the integer appears correctly on the command line /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestInteger() { object fakeTaskInstance = CreateFakeTask(); XamlTestHelpers.SetProperty(fakeTaskInstance, "BasicInteger", 2); string expectedResult = "/always /Bi2 /Cr:CT"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); } // complex tests /// <summary> /// Tests the (full) functionality of a reversible property /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestComplexReversible() { // When flag is set to false object fakeTaskInstance = CreateFakeTask(); XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexReversible", false); string expectedResult = "/always /Cr:CF"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); // When flag is set to true fakeTaskInstance = CreateFakeTask(); XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexReversible", true); expectedResult = "/always /Cr:CT"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); } [Fact] [Trait("Category", "mono-osx-failing")] public void TestComplexString() { // check to see that the resulting value is good object fakeTaskInstance = CreateFakeTask(); XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexString", "LegalValue1"); string expectedResult = "/always /Cr:CT /Lv1"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); } /// <summary> /// Tests the functionality of a string type property /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestComplexStringArray() { object fakeTaskInstance = CreateFakeTask(); string[] fakeArray = new string[] { "FakeFile1", "FakeFile2", "FakeFile3" }; XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexStringArray", new object[] { fakeArray }); string expectedResult = "/always /Cr:CT /CsaFakeFile1;FakeFile2;FakeFile3"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); } [Fact] [Trait("Category", "mono-osx-failing")] public void TestComplexIntegerLessThanMin() { Assert.Throws<InvalidOperationException>(() => { object fakeTaskInstance = CreateFakeTask(); XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexInteger", 2); } ); } [Fact] [Trait("Category", "mono-osx-failing")] public void TestComplexIntegerGreaterThanMax() { Assert.Throws<InvalidOperationException>(() => { object fakeTaskInstance = CreateFakeTask(); XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexInteger", 256); string expectedResult = "/always /Ci256 /Cr:CT"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); } ); } [Fact] [Trait("Category", "mono-osx-failing")] public void TestComplexIntegerWithinRange() { object fakeTaskInstance = CreateFakeTask(); XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexInteger", 128); string expectedResult = "/always /Cr:CT /Ci128"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); } /// <summary> /// This method checks the generated command line against the expected command line /// </summary> /// <param name="expected"></param> /// <param name="actual"></param> /// <returns>true if the two are the same, false if they are different</returns> private void CheckCommandLine(string expected, string actual) { Assert.Equal(expected, actual); } /// <summary> /// XamlTaskFactory does not, in and of itself, support the idea of "always" switches or default values. At least /// for Dev10, the workaround is to create a property as usual, and then specify the required values in the .props /// file. Since these unit tests are just testing the task itself, this method serves as our ".props file". /// </summary> public object CreateFakeTask() { object fakeTaskInstance = _fakeTaskDll.CreateInstance("XamlTaskNamespace.FakeTask"); XamlTestHelpers.SetProperty(fakeTaskInstance, "Always", true); XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexReversible", true); return fakeTaskInstance; } } /// <summary> /// Tests for XamlDataDrivenToolTask / XamlTaskFactory in the context of a project file. /// </summary> public class ProjectFileTests { /// <summary> /// Tests that when a call to a XamlDataDrivenTask fails, the commandline is reported in the error message. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void CommandLineErrorsReportFullCommandlineAmpersandTemp() { string projectFile = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` DefaultTargets=`XamlTaskFactory` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <UsingTask TaskName=`TestTask` TaskFactory=`XamlTaskFactory` AssemblyName=`Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`> <Task> <![CDATA[ <ProjectSchemaDefinitions xmlns=`clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework` xmlns:x=`http://schemas.microsoft.com/winfx/2006/xaml` xmlns:sys=`clr-namespace:System;assembly=mscorlib` xmlns:impl=`clr-namespace:Microsoft.VisualStudio.Project.Contracts.Implementation;assembly=Microsoft.VisualStudio.Project.Contracts.Implementation`> <Rule Name=`TestTask` ToolName=`findstr.exe`> <StringProperty Name=`test` /> </Rule> </ProjectSchemaDefinitions> ]]> </Task> </UsingTask> <Target Name=`XamlTaskFactory`> <TestTask CommandLineTemplate='findstr'/> </Target> </Project>"; string directoryWithAmpersand = "xaml&datadriven"; string newTmp = Path.Combine(Path.GetTempPath(), directoryWithAmpersand); string oldTmp = Environment.GetEnvironmentVariable("TMP"); try { Directory.CreateDirectory(newTmp); Environment.SetEnvironmentVariable("TMP", newTmp); Project p = ObjectModelHelpers.CreateInMemoryProject(projectFile); MockLogger logger = new MockLogger(); bool success = p.Build(logger); Assert.False(success); logger.AssertLogContains("FINDSTR"); // Should not be logging ToolTask.ToolCommandFailed, should be logging Xaml.CommandFailed logger.AssertLogDoesntContain("MSB6006"); logger.AssertLogContains("MSB3721"); } finally { Environment.SetEnvironmentVariable("TMP", oldTmp); ObjectModelHelpers.DeleteDirectory(newTmp); if (Directory.Exists(newTmp)) FileUtilities.DeleteWithoutTrailingBackslash(newTmp); } } /// <summary> /// Tests that when a call to a XamlDataDrivenTask fails, the commandline is reported in the error message. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void CommandLineErrorsReportFullCommandline() { string projectFile = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` DefaultTargets=`XamlTaskFactory` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <UsingTask TaskName=`TestTask` TaskFactory=`XamlTaskFactory` AssemblyName=`Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`> <Task> <![CDATA[ <ProjectSchemaDefinitions xmlns=`clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework` xmlns:x=`http://schemas.microsoft.com/winfx/2006/xaml` xmlns:sys=`clr-namespace:System;assembly=mscorlib` xmlns:impl=`clr-namespace:Microsoft.VisualStudio.Project.Contracts.Implementation;assembly=Microsoft.VisualStudio.Project.Contracts.Implementation`> <Rule Name=`TestTask` ToolName=`echoparameters.exe`> <StringProperty Name=`test` /> </Rule> </ProjectSchemaDefinitions> ]]> </Task> </UsingTask> <Target Name=`XamlTaskFactory`> <TestTask CommandLineTemplate=`where /x` /> </Target> </Project>"; Project p = ObjectModelHelpers.CreateInMemoryProject(projectFile); MockLogger logger = new MockLogger(); bool success = p.Build(logger); Assert.False(success); // "Build should have failed" // Should not be logging ToolTask.ToolCommandFailed, should be logging Xaml.CommandFailed logger.AssertLogDoesntContain("MSB6006"); logger.AssertLogContains("MSB3721"); } /// <summary> /// Tests that when a call to a XamlDataDrivenTask fails, the commandline is reported in the error message. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void SquareBracketEscaping() { string projectFile = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` DefaultTargets=`XamlTaskFactory` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <UsingTask TaskName=`TestTask` TaskFactory=`XamlTaskFactory` AssemblyName=`Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`> <Task> <![CDATA[ <ProjectSchemaDefinitions xmlns=`clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework` xmlns:x=`http://schemas.microsoft.com/winfx/2006/xaml` xmlns:sys=`clr-namespace:System;assembly=mscorlib` xmlns:impl=`clr-namespace:Microsoft.VisualStudio.Project.Contracts.Implementation;assembly=Microsoft.VisualStudio.Project.Contracts.Implementation`> <Rule Name=`TestTask` ToolName=`echoparameters.exe`> <StringProperty Name=`test` /> </Rule> </ProjectSchemaDefinitions> ]]> </Task> </UsingTask> <Target Name=`XamlTaskFactory`> <TestTask CommandLineTemplate=`echo 1) [test] end` test=`value` /> <TestTask CommandLineTemplate=`echo 2) [[[test] end` test=`value` /> <TestTask CommandLineTemplate=`echo 3) [ [test] end` test=`value` /> <TestTask CommandLineTemplate=`echo 4) [ [test] [test] end` test=`value` /> <TestTask CommandLineTemplate=`echo 5) [test]] end` test=`value` /> <TestTask CommandLineTemplate=`echo 6) [[test]] end` test=`value` /> <TestTask CommandLineTemplate=`echo 7) [[[test]] end` test=`value` /> <TestTask CommandLineTemplate=`echo 8) [notaproperty] end` test=`value` /> <TestTask CommandLineTemplate=`echo 9) [[[notaproperty] end` test=`value` /> <TestTask CommandLineTemplate=`echo 10) [ [notaproperty] end` test=`value` /> <TestTask CommandLineTemplate=`echo 11) [ [nap] [nap] end` test=`value` /> <TestTask CommandLineTemplate=`echo 12) [notaproperty]] end` test=`value` /> <TestTask CommandLineTemplate=`echo 13) [[notaproperty]] end` test=`value` /> <TestTask CommandLineTemplate=`echo 14) [[[notaproperty]] end` test=`value` /> </Target> </Project>"; Project p = ObjectModelHelpers.CreateInMemoryProject(projectFile); MockLogger logger = new MockLogger(); bool success = p.Build(logger); Assert.True(success); // "Build should have succeeded" logger.AssertLogContains("echo 1) value end"); logger.AssertLogContains("echo 2) [value end"); logger.AssertLogContains("echo 3) [ value end"); logger.AssertLogContains("echo 4) [ value value end"); logger.AssertLogContains("echo 5) value] end"); logger.AssertLogContains("echo 6) [test]] end"); logger.AssertLogContains("echo 7) [value] end"); logger.AssertLogContains("echo 8) [notaproperty] end"); logger.AssertLogContains("echo 9) [[notaproperty] end"); logger.AssertLogContains("echo 10) [ [notaproperty] end"); logger.AssertLogContains("echo 11) [ [nap] [nap] end"); logger.AssertLogContains("echo 12) [notaproperty]] end"); logger.AssertLogContains("echo 13) [notaproperty]] end"); logger.AssertLogContains("echo 14) [[notaproperty]] end"); } } }
// 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.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using WebsitePanel.EnterpriseServer; namespace WebsitePanel.Portal { public partial class SettingsEditor : WebsitePanelModuleBase { private string SettingsName { get { return Request["SettingsName"]; } } IUserSettingsEditorControl ctlSettings; protected void Page_Load(object sender, EventArgs e) { // load settings control LoadSettingsControl(); // entry point try { if (!IsPostBack) { // save referrer URL if(Request.UrlReferrer != null) ViewState["ReturnURL"] = Request.UrlReferrer.ToString(); // bind settings BindSettings(); } } catch (Exception ex) { ShowErrorMessage("USER_SETTINGS_GET", ex); return; } } private void BindSettings() { // load user settings UserSettings settings = ES.Services.Users.GetUserSettings(PanelSecurity.SelectedUserId, SettingsName); ddlOverride.SelectedIndex = (settings.UserId == PanelSecurity.SelectedUserId) ? 1 : 0; ToggleControls(); // bind settings ctlSettings.BindSettings(settings); } protected void ddlOverride_SelectedIndexChanged(object sender, EventArgs e) { if (ddlOverride.SelectedIndex == 0) // use host settings { // delete current settings UserSettings settings = new UserSettings(); settings.UserId = PanelSecurity.SelectedUserId; settings.SettingsName = SettingsName; ES.Services.Users.UpdateUserSettings(settings); // rebind settings BindSettings(); } else if (!SettingsName.Equals("ServiceLevels")) { ToggleControls(); } } private void ToggleControls() { ddlOverride.Enabled = (PanelSecurity.SelectedUser.Role != UserRole.Administrator); // check if we should enable controls bool enabled = (ddlOverride.SelectedIndex == 1); // enable/disable controls EnableControlRecursively((Control)ctlSettings, enabled); } private void EnableControlRecursively(Control ctrl, bool enabled) { WebControl wc = ctrl as WebControl; if (wc != null && !(wc is Label)) wc.Enabled = enabled; // process children foreach (Control childCtrl in ctrl.Controls) EnableControlRecursively(childCtrl, enabled); } private void SaveSettings() { try { UserSettings settings = new UserSettings(); settings.UserId = PanelSecurity.SelectedUserId; settings.SettingsName = SettingsName; // set properties if (ddlOverride.SelectedIndex == 1) { // gather settings from the control // if overriden ctlSettings.SaveSettings(settings); // check settings foreach (Control control in settingsPlace.Controls) { string[] parts; if (control is SettingsWebsitePanelPolicy) { if (!PasswordPolicyValidation(settings["PasswordPolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } } if (control is SettingsWebPolicy) { if (!UserNamePolicyValidation(settings["AnonymousAccountPolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } if (!UserNamePolicyValidation(settings["VirtDirNamePolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } if (!UserNamePolicyValidation(settings["FrontPageAccountPolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } if (!PasswordPolicyValidation(settings["FrontPagePasswordPolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } if (!UserNamePolicyValidation(settings["SecuredUserNamePolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } if (!PasswordPolicyValidation(settings["SecuredUserPasswordPolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } if (!UserNamePolicyValidation(settings["SecuredGroupNamePolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } } if (control is SettingsFtpPolicy) { if (!UserNamePolicyValidation(settings["UserNamePolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } if (!PasswordPolicyValidation(settings["UserPasswordPolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } } if (control is SettingsMailPolicy) { if (!UserNamePolicyValidation(settings["AccountNamePolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } if (!PasswordPolicyValidation(settings["AccountPasswordPolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } } if (control is SettingsMsSqlPolicy) { if (!UserNamePolicyValidation(settings["DatabaseNamePolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } if (!UserNamePolicyValidation(settings["UserNamePolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } if (!PasswordPolicyValidation(settings["UserPasswordPolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } } if (control is SettingsMySqlPolicy) { if (!UserNamePolicyValidation(settings["DatabaseNamePolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } if (!UserNamePolicyValidation(settings["UserNamePolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } parts = settings["UserNamePolicy"].Split(';'); if (Utils.ParseInt(parts[3]) > 40) { ShowWarningMessage("MySQL_USERNAME_MAX_LENGTH"); return; } if (!PasswordPolicyValidation(settings["UserPasswordPolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } } if (control is SettingsSharePointPolicy) { if (!UserNamePolicyValidation(settings["GroupNamePolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } if (!UserNamePolicyValidation(settings["UserNamePolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } if (!PasswordPolicyValidation(settings["UserPasswordPolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } } if (control is SettingsOperatingSystemPolicy) { if (!UserNamePolicyValidation(settings["DsnNamePolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } } if (control is SettingsExchangePolicy) { if (!PasswordPolicyValidation(settings["MailboxPasswordPolicy"])) { ShowWarningMessage("WRONG_POLICIES_VALUES"); return; } } } } // end if overriden int result = ES.Services.Users.UpdateUserSettings(settings); if (result < 0) { ShowResultMessage(result); return; } RedirectBack(); } catch (Exception ex) { ShowErrorMessage("USER_SETTINGS_UPDATE", ex); return; } } private static bool PasswordPolicyValidation(string passwordPolicy) { string[] parts = passwordPolicy.Split(';'); return (Utils.ParseInt(parts[1]) < Utils.ParseInt(parts[2]) && Utils.ParseInt(parts[3]) < Utils.ParseInt(parts[2]) && Utils.ParseInt(parts[4]) < Utils.ParseInt(parts[2]) && Utils.ParseInt(parts[5]) < Utils.ParseInt(parts[2]) && (Utils.ParseInt(parts[3]) + Utils.ParseInt(parts[4]) + Utils.ParseInt(parts[5])) <= Utils.ParseInt(parts[2])); } private static bool UserNamePolicyValidation(string usernamePolicy) { string[] parts = usernamePolicy.Split(';'); return (Utils.ParseInt(parts[2]) < Utils.ParseInt(parts[3])); } private void LoadSettingsControl() { string controlName = Request["SettingsControl"]; if (!String.IsNullOrEmpty(controlName)) { string currPath = this.AppRelativeVirtualPath; currPath = currPath.Substring(0, currPath.LastIndexOf("/")); string ctrlPath = currPath + "/" + controlName + ".ascx"; Control ctrl = Page.LoadControl(ctrlPath); ctlSettings = (IUserSettingsEditorControl)ctrl; settingsPlace.Controls.Add(ctrl); } else { RedirectBack(); } } protected void btnSave_Click(object sender, EventArgs e) { SaveSettings(); } protected void btnCancel_Click(object sender, EventArgs e) { RedirectBack(); } private void RedirectBack() { if (ViewState["ReturnURL"] != null) Response.Redirect((string)ViewState["ReturnURL"]); else RedirectToBrowsePage(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Scenes; using OpenSim.Tests.Common; namespace OpenSim.Region.Framework.Scenes.Tests { /// <summary> /// Basic scene object status tests /// </summary> [TestFixture] public class SceneObjectStatusTests : OpenSimTestCase { private TestScene m_scene; private UUID m_ownerId = TestHelpers.ParseTail(0x1); private SceneObjectGroup m_so1; private SceneObjectGroup m_so2; [SetUp] public void Init() { m_scene = new SceneHelpers().SetupScene(); m_so1 = SceneHelpers.CreateSceneObject(1, m_ownerId, "so1", 0x10); m_so2 = SceneHelpers.CreateSceneObject(1, m_ownerId, "so2", 0x20); } [Test] public void TestSetTemporary() { TestHelpers.InMethod(); m_scene.AddSceneObject(m_so1); m_so1.ScriptSetTemporaryStatus(true); // Is this really the correct flag? Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.TemporaryOnRez)); Assert.That(m_so1.Backup, Is.False); // Test setting back to non-temporary m_so1.ScriptSetTemporaryStatus(false); Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.None)); Assert.That(m_so1.Backup, Is.True); } [Test] public void TestSetPhantomSinglePrim() { TestHelpers.InMethod(); m_scene.AddSceneObject(m_so1); SceneObjectPart rootPart = m_so1.RootPart; Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None)); m_so1.ScriptSetPhantomStatus(true); // Console.WriteLine("so.RootPart.Flags [{0}]", so.RootPart.Flags); Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Phantom)); m_so1.ScriptSetPhantomStatus(false); Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None)); } [Test] public void TestSetNonPhysicsVolumeDetectSinglePrim() { TestHelpers.InMethod(); m_scene.AddSceneObject(m_so1); SceneObjectPart rootPart = m_so1.RootPart; Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None)); m_so1.ScriptSetVolumeDetect(true); // Console.WriteLine("so.RootPart.Flags [{0}]", so.RootPart.Flags); Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Phantom)); m_so1.ScriptSetVolumeDetect(false); Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None)); } [Test] public void TestSetPhysicsSinglePrim() { TestHelpers.InMethod(); m_scene.AddSceneObject(m_so1); SceneObjectPart rootPart = m_so1.RootPart; Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None)); m_so1.ScriptSetPhysicsStatus(true); Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Physics)); m_so1.ScriptSetPhysicsStatus(false); Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None)); } [Test] public void TestSetPhysicsVolumeDetectSinglePrim() { TestHelpers.InMethod(); m_scene.AddSceneObject(m_so1); SceneObjectPart rootPart = m_so1.RootPart; Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None)); m_so1.ScriptSetPhysicsStatus(true); m_so1.ScriptSetVolumeDetect(true); Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Phantom | PrimFlags.Physics)); m_so1.ScriptSetVolumeDetect(false); Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Physics)); } [Test] public void TestSetPhysicsLinkset() { TestHelpers.InMethod(); m_scene.AddSceneObject(m_so1); m_scene.AddSceneObject(m_so2); m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId }); m_so1.ScriptSetPhysicsStatus(true); Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics)); Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics)); m_so1.ScriptSetPhysicsStatus(false); Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.None)); Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.None)); m_so1.ScriptSetPhysicsStatus(true); Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics)); Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics)); } /// <summary> /// Test that linking results in the correct physical status for all linkees. /// </summary> [Test] public void TestLinkPhysicsBothPhysical() { TestHelpers.InMethod(); m_scene.AddSceneObject(m_so1); m_scene.AddSceneObject(m_so2); m_so1.ScriptSetPhysicsStatus(true); m_so2.ScriptSetPhysicsStatus(true); m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId }); Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics)); Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics)); } /// <summary> /// Test that linking results in the correct physical status for all linkees. /// </summary> [Test] public void TestLinkPhysicsRootPhysicalOnly() { TestHelpers.InMethod(); m_scene.AddSceneObject(m_so1); m_scene.AddSceneObject(m_so2); m_so1.ScriptSetPhysicsStatus(true); m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId }); Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics)); Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics)); } /// <summary> /// Test that linking results in the correct physical status for all linkees. /// </summary> [Test] public void TestLinkPhysicsChildPhysicalOnly() { TestHelpers.InMethod(); m_scene.AddSceneObject(m_so1); m_scene.AddSceneObject(m_so2); m_so2.ScriptSetPhysicsStatus(true); m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId }); Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.None)); Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.None)); } } }
using System; using UnityEngine; namespace UnityStandardAssets.ImageEffects { public enum LensflareStyle34 { Ghosting = 0, Anamorphic = 1, Combined = 2, } public enum TweakMode34 { Basic = 0, Complex = 1, } public enum HDRBloomMode { Auto = 0, On = 1, Off = 2, } public enum BloomScreenBlendMode { Screen = 0, Add = 1, } [ExecuteInEditMode] [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Bloom and Glow/BloomAndFlares (3.5, Deprecated)")] public class BloomAndFlares : PostEffectsBase { public TweakMode34 tweakMode = 0; public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add; public HDRBloomMode hdr = HDRBloomMode.Auto; private bool doHdr = false; public float sepBlurSpread = 1.5f; public float useSrcAlphaAsMask = 0.5f; public float bloomIntensity = 1.0f; public float bloomThreshold = 0.5f; public int bloomBlurIterations = 2; public bool lensflares = false; public int hollywoodFlareBlurIterations = 2; public LensflareStyle34 lensflareMode = (LensflareStyle34)1; public float hollyStretchWidth = 3.5f; public float lensflareIntensity = 1.0f; public float lensflareThreshold = 0.3f; public Color flareColorA = new Color(0.4f, 0.4f, 0.8f, 0.75f); public Color flareColorB = new Color(0.4f, 0.8f, 0.8f, 0.75f); public Color flareColorC = new Color(0.8f, 0.4f, 0.8f, 0.75f); public Color flareColorD = new Color(0.8f, 0.4f, 0.0f, 0.75f); public Texture2D lensFlareVignetteMask; public Shader lensFlareShader; private Material lensFlareMaterial; public Shader vignetteShader; private Material vignetteMaterial; public Shader separableBlurShader; private Material separableBlurMaterial; public Shader addBrightStuffOneOneShader; private Material addBrightStuffBlendOneOneMaterial; public Shader screenBlendShader; private Material screenBlend; public Shader hollywoodFlaresShader; private Material hollywoodFlaresMaterial; public Shader brightPassFilterShader; private Material brightPassFilterMaterial; public override bool CheckResources() { CheckSupport(false); screenBlend = CheckShaderAndCreateMaterial(screenBlendShader, screenBlend); lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader, lensFlareMaterial); vignetteMaterial = CheckShaderAndCreateMaterial(vignetteShader, vignetteMaterial); separableBlurMaterial = CheckShaderAndCreateMaterial(separableBlurShader, separableBlurMaterial); addBrightStuffBlendOneOneMaterial = CheckShaderAndCreateMaterial(addBrightStuffOneOneShader, addBrightStuffBlendOneOneMaterial); hollywoodFlaresMaterial = CheckShaderAndCreateMaterial(hollywoodFlaresShader, hollywoodFlaresMaterial); brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial); if (!isSupported) ReportAutoDisable(); return isSupported; } void OnRenderImage(RenderTexture source, RenderTexture destination) { if (CheckResources() == false) { Graphics.Blit(source, destination); return; } // screen blend is not supported when HDR is enabled (will cap values) doHdr = false; if (hdr == HDRBloomMode.Auto) doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().allowHDR; else { doHdr = hdr == HDRBloomMode.On; } doHdr = doHdr && supportHDRTextures; BloomScreenBlendMode realBlendMode = screenBlendMode; if (doHdr) { realBlendMode = BloomScreenBlendMode.Add; } var rtFormat = (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default; RenderTexture halfRezColor = RenderTexture.GetTemporary(source.width / 2, source.height / 2, 0, rtFormat); RenderTexture quarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat); RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat); RenderTexture thirdQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat); float widthOverHeight = (1.0f * source.width) / (1.0f * source.height); float oneOverBaseSize = 1.0f / 512.0f; // downsample Graphics.Blit(source, halfRezColor, screenBlend, 2); // <- 2 is stable downsample Graphics.Blit(halfRezColor, quarterRezColor, screenBlend, 2); // <- 2 is stable downsample RenderTexture.ReleaseTemporary(halfRezColor); // cut colors (thresholding) BrightFilter(bloomThreshold, useSrcAlphaAsMask, quarterRezColor, secondQuarterRezColor); quarterRezColor.DiscardContents(); // blurring if (bloomBlurIterations < 1) bloomBlurIterations = 1; for (int iter = 0; iter < bloomBlurIterations; iter++) { float spreadForPass = (1.0f + (iter * 0.5f)) * sepBlurSpread; separableBlurMaterial.SetVector("offsets", new Vector4(0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f)); RenderTexture src = iter == 0 ? secondQuarterRezColor : quarterRezColor; Graphics.Blit(src, thirdQuarterRezColor, separableBlurMaterial); src.DiscardContents(); separableBlurMaterial.SetVector("offsets", new Vector4((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(thirdQuarterRezColor, quarterRezColor, separableBlurMaterial); thirdQuarterRezColor.DiscardContents(); } // lens flares: ghosting, anamorphic or a combination if (lensflares) { if (lensflareMode == 0) { BrightFilter(lensflareThreshold, 0.0f, quarterRezColor, thirdQuarterRezColor); quarterRezColor.DiscardContents(); // smooth a little, this needs to be resolution dependent /* separableBlurMaterial.SetVector ("offsets", Vector4 (0.0ff, (2.0ff) / (1.0ff * quarterRezColor.height), 0.0ff, 0.0ff)); Graphics.Blit (thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial); separableBlurMaterial.SetVector ("offsets", Vector4 ((2.0ff) / (1.0ff * quarterRezColor.width), 0.0ff, 0.0ff, 0.0ff)); Graphics.Blit (secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial); */ // no ugly edges! Vignette(0.975f, thirdQuarterRezColor, secondQuarterRezColor); thirdQuarterRezColor.DiscardContents(); BlendFlares(secondQuarterRezColor, quarterRezColor); secondQuarterRezColor.DiscardContents(); } // (b) hollywood/anamorphic flares? else { // thirdQuarter has the brightcut unblurred colors // quarterRezColor is the blurred, brightcut buffer that will end up as bloom hollywoodFlaresMaterial.SetVector("_threshold", new Vector4(lensflareThreshold, 1.0f / (1.0f - lensflareThreshold), 0.0f, 0.0f)); hollywoodFlaresMaterial.SetVector("tintColor", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity); Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 2); thirdQuarterRezColor.DiscardContents(); Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 3); secondQuarterRezColor.DiscardContents(); hollywoodFlaresMaterial.SetVector("offsets", new Vector4((sepBlurSpread * 1.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth); Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1); thirdQuarterRezColor.DiscardContents(); hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 2.0f); Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 1); secondQuarterRezColor.DiscardContents(); hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 4.0f); Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1); thirdQuarterRezColor.DiscardContents(); if (lensflareMode == (LensflareStyle34)1) { for (int itera = 0; itera < hollywoodFlareBlurIterations; itera++) { separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial); secondQuarterRezColor.DiscardContents(); separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial); thirdQuarterRezColor.DiscardContents(); } AddTo(1.0f, secondQuarterRezColor, quarterRezColor); secondQuarterRezColor.DiscardContents(); } else { // (c) combined for (int ix = 0; ix < hollywoodFlareBlurIterations; ix++) { separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial); secondQuarterRezColor.DiscardContents(); separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial); thirdQuarterRezColor.DiscardContents(); } Vignette(1.0f, secondQuarterRezColor, thirdQuarterRezColor); secondQuarterRezColor.DiscardContents(); BlendFlares(thirdQuarterRezColor, secondQuarterRezColor); thirdQuarterRezColor.DiscardContents(); AddTo(1.0f, secondQuarterRezColor, quarterRezColor); secondQuarterRezColor.DiscardContents(); } } } // screen blend bloom results to color buffer screenBlend.SetFloat("_Intensity", bloomIntensity); screenBlend.SetTexture("_ColorBuffer", source); Graphics.Blit(quarterRezColor, destination, screenBlend, (int)realBlendMode); RenderTexture.ReleaseTemporary(quarterRezColor); RenderTexture.ReleaseTemporary(secondQuarterRezColor); RenderTexture.ReleaseTemporary(thirdQuarterRezColor); } private void AddTo(float intensity_, RenderTexture from, RenderTexture to) { addBrightStuffBlendOneOneMaterial.SetFloat("_Intensity", intensity_); Graphics.Blit(from, to, addBrightStuffBlendOneOneMaterial); } private void BlendFlares(RenderTexture from, RenderTexture to) { lensFlareMaterial.SetVector("colorA", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity); lensFlareMaterial.SetVector("colorB", new Vector4(flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity); lensFlareMaterial.SetVector("colorC", new Vector4(flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity); lensFlareMaterial.SetVector("colorD", new Vector4(flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity); Graphics.Blit(from, to, lensFlareMaterial); } private void BrightFilter(float thresh, float useAlphaAsMask, RenderTexture from, RenderTexture to) { if (doHdr) brightPassFilterMaterial.SetVector("threshold", new Vector4(thresh, 1.0f, 0.0f, 0.0f)); else brightPassFilterMaterial.SetVector("threshold", new Vector4(thresh, 1.0f / (1.0f - thresh), 0.0f, 0.0f)); brightPassFilterMaterial.SetFloat("useSrcAlphaAsMask", useAlphaAsMask); Graphics.Blit(from, to, brightPassFilterMaterial); } private void Vignette(float amount, RenderTexture from, RenderTexture to) { if (lensFlareVignetteMask) { screenBlend.SetTexture("_ColorBuffer", lensFlareVignetteMask); Graphics.Blit(from, to, screenBlend, 3); } else { vignetteMaterial.SetFloat("vignetteIntensity", amount); Graphics.Blit(from, to, vignetteMaterial); } } } }
// 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.IO; using System.Reflection; using System.Threading.Tasks; using System.Xml; using Microsoft.Build.BackEnd; using Microsoft.Build.BackEnd.SdkResolution; using Microsoft.Build.Collections; using Microsoft.Build.Engine.UnitTests.BackEnd; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using ElementLocation = Microsoft.Build.Construction.ElementLocation; using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService; using LegacyThreadingData = Microsoft.Build.Execution.LegacyThreadingData; using Xunit; using Xunit.Abstractions; namespace Microsoft.Build.UnitTests.BackEnd { /// <summary> /// Unit tests for the TaskBuilder component /// </summary> public class TaskBuilder_Tests : ITargetBuilderCallback { /// <summary> /// The mock component host and logger /// </summary> private MockHost _host; private readonly ITestOutputHelper _testOutput; /// <summary> /// The temporary project we use to run the test /// </summary> private ProjectInstance _testProject; /// <summary> /// Prepares the environment for the test. /// </summary> public TaskBuilder_Tests(ITestOutputHelper output) { _host = new MockHost(); _testOutput = output; _testProject = CreateTestProject(); } /********************************************************************************* * * OUTPUT PARAMS * *********************************************************************************/ /// <summary> /// Verifies that we do look up the task during execute when the condition is true. /// </summary> [Fact] public void TasksAreDiscoveredWhenTaskConditionTrue() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <NonExistantTask Condition=""'1'=='1'""/> <Message Text='Made it'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t", loggers); logger.AssertLogContains("MSB4036"); logger.AssertLogDoesntContain("Made it"); } /// <summary> /// Tests that when the task condition is false, Execute still returns true even though we never loaded /// the task. We verify that we never loaded the task because if we did try, the task load itself would /// have failed, resulting in an error. /// </summary> [Fact] public void TasksNotDiscoveredWhenTaskConditionFalse() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <NonExistantTask Condition=""'1'=='2'""/> <Message Text='Made it'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t", loggers); logger.AssertLogContains("Made it"); } /// <summary> /// Verify when task outputs are overridden the override messages are correctly displayed /// </summary> [Fact] public void OverridePropertiesInCreateProperty() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <EmbeddedResource Include='a.resx'> <LogicalName>foo</LogicalName> </EmbeddedResource> <EmbeddedResource Include='b.resx'> <LogicalName>bar</LogicalName> </EmbeddedResource> <EmbeddedResource Include='c.resx'> <LogicalName>barz</LogicalName> </EmbeddedResource> </ItemGroup> <Target Name='t'> <CreateProperty Value=""@(EmbeddedResource->'/assemblyresource:%(Identity),%(LogicalName)', ' ')"" Condition=""'%(LogicalName)' != '' ""> <Output TaskParameter=""Value"" PropertyName=""LinkSwitches""/> </CreateProperty> <Message Text='final:[$(LinkSwitches)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t", loggers); logger.AssertLogContains(new string[] { "final:[/assemblyresource:c.resx,barz]" }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TaskStarted", "CreateProperty") }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:a.resx,foo", "/assemblyresource:b.resx,bar") }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:b.resx,bar", "/assemblyresource:c.resx,barz") }); } /// <summary> /// Verify that when a task outputs are inferred the override messages are displayed /// </summary> [Fact] public void OverridePropertiesInInferredCreateProperty() { string[] files = null; try { files = ObjectModelHelpers.GetTempFiles(2, new DateTime(2005, 1, 1)); MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <i Include='" + files[0] + "'><output>" + files[1] + @"</output></i> </ItemGroup> <ItemGroup> <EmbeddedResource Include='a.resx'> <LogicalName>foo</LogicalName> </EmbeddedResource> <EmbeddedResource Include='b.resx'> <LogicalName>bar</LogicalName> </EmbeddedResource> <EmbeddedResource Include='c.resx'> <LogicalName>barz</LogicalName> </EmbeddedResource> </ItemGroup> <Target Name='t2' DependsOnTargets='t'> <Message Text='final:[$(LinkSwitches)]'/> </Target> <Target Name='t' Inputs='%(i.Identity)' Outputs='%(i.Output)'> <Message Text='start:[Hello]'/> <CreateProperty Value=""@(EmbeddedResource->'/assemblyresource:%(Identity),%(LogicalName)', ' ')"" Condition=""'%(LogicalName)' != '' ""> <Output TaskParameter=""Value"" PropertyName=""LinkSwitches""/> </CreateProperty> <Message Text='end:[hello]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t2", loggers); // We should only see messages from the second target, as the first is only inferred logger.AssertLogDoesntContain("start:"); logger.AssertLogDoesntContain("end:"); logger.AssertLogContains(new string[] { "final:[/assemblyresource:c.resx,barz]" }); logger.AssertLogDoesntContain(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TaskStarted", "CreateProperty")); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:a.resx,foo", "/assemblyresource:b.resx,bar") }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:b.resx,bar", "/assemblyresource:c.resx,barz") }); } finally { ObjectModelHelpers.DeleteTempFiles(files); } } /// <summary> /// Tests that tasks batch on outputs correctly. /// </summary> [Fact] public void TaskOutputBatching() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <TaskParameterItem Include=""foo""> <ParameterName>Value</ParameterName> <ParameterName2>Include</ParameterName2> <PropertyName>MetadataProperty</PropertyName> <ItemType>MetadataItem</ItemType> </TaskParameterItem> </ItemGroup> <Target Name='Build'> <CreateProperty Value=""@(TaskParameterItem)""> <Output TaskParameter=""Value"" PropertyName=""Property1""/> </CreateProperty> <Message Text='Property1=[$(Property1)]' /> <CreateProperty Value=""@(TaskParameterItem)""> <Output TaskParameter=""%(TaskParameterItem.ParameterName)"" PropertyName=""Property2""/> </CreateProperty> <Message Text='Property2=[$(Property2)]' /> <CreateProperty Value=""@(TaskParameterItem)""> <Output TaskParameter=""Value"" PropertyName=""%(TaskParameterItem.PropertyName)""/> </CreateProperty> <Message Text='MetadataProperty=[$(MetadataProperty)]' /> <CreateItem Include=""@(TaskParameterItem)""> <Output TaskParameter=""Include"" ItemName=""TestItem1""/> </CreateItem> <Message Text='TestItem1=[@(TestItem1)]' /> <CreateItem Include=""@(TaskParameterItem)""> <Output TaskParameter=""%(TaskParameterItem.ParameterName2)"" ItemName=""TestItem2""/> </CreateItem> <Message Text='TestItem2=[@(TestItem2)]' /> <CreateItem Include=""@(TaskParameterItem)""> <Output TaskParameter=""Include"" ItemName=""%(TaskParameterItem.ItemType)""/> </CreateItem> <Message Text='MetadataItem=[@(MetadataItem)]' /> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build(loggers); logger.AssertLogContains("Property1=[foo]"); logger.AssertLogContains("Property2=[foo]"); logger.AssertLogContains("MetadataProperty=[foo]"); logger.AssertLogContains("TestItem1=[foo]"); logger.AssertLogContains("TestItem2=[foo]"); logger.AssertLogContains("MetadataItem=[foo]"); } /// <summary> /// MSbuildLastTaskResult property contains true or false indicating /// the success or failure of the last task. /// </summary> [Fact] public void MSBuildLastTaskResult() { string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project DefaultTargets='t2' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <Message Text='[start:$(MSBuildLastTaskResult)]'/> <!-- Should be blank --> <Warning Text='warning'/> <Message Text='[0:$(MSBuildLastTaskResult)]'/> <!-- Should be true, only a warning--> <!-- task's Execute returns false --> <Copy SourceFiles='|' DestinationFolder='c:\' ContinueOnError='true' /> <PropertyGroup> <p>$(MSBuildLastTaskResult)</p> </PropertyGroup> <Message Text='[1:$(MSBuildLastTaskResult)]'/> <!-- Should be false: propertygroup did not reset it --> <Message Text='[p:$(p)]'/> <!-- Should be false as stored earlier --> <Message Text='[2:$(MSBuildLastTaskResult)]'/> <!-- Message succeeded, should now be true --> </Target> <Target Name='t2' DependsOnTargets='t'> <Message Text='[3:$(MSBuildLastTaskResult)]'/> <!-- Should still have true --> <!-- check Error task as well --> <Error Text='error' ContinueOnError='true' /> <Message Text='[4:$(MSBuildLastTaskResult)]'/> <!-- Should be false --> <!-- trigger OnError target, ContinueOnError is false --> <Error Text='error2'/> <OnError ExecuteTargets='t3'/> </Target> <Target Name='t3' > <Message Text='[5:$(MSBuildLastTaskResult)]'/> <!-- Should be false --> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); MockLogger logger = new MockLogger(); loggers.Add(logger); project.Build("t2", loggers); logger.AssertLogContains("[start:]"); logger.AssertLogContains("[0:true]"); logger.AssertLogContains("[1:false]"); logger.AssertLogContains("[p:false]"); logger.AssertLogContains("[2:true]"); logger.AssertLogContains("[3:true]"); logger.AssertLogContains("[4:false]"); logger.AssertLogContains("[4:false]"); } /// <summary> /// Verifies that we can add "recursivedir" built-in metadata as target outputs. /// This is to support wildcards in CreateItem. Allowing anything /// else could let the item get corrupt (inconsistent values for Filename and FullPath, for example) /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] [Trait("Category", "mono-osx-failing")] public void TasksCanAddRecursiveDirBuiltInMetadata() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <CreateItem Include='$(programfiles)\reference assemblies\**\*.dll;'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> <Message Text='@(x)'/> <Message Text='[%(x.RecursiveDir)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.True(result); logger.AssertLogDoesntContain("[]"); logger.AssertLogDoesntContain("MSB4118"); logger.AssertLogDoesntContain("MSB3031"); } /// <summary> /// Verify CreateItem prevents adding any built-in metadata explicitly, even recursivedir. /// </summary> [Fact] public void OtherBuiltInMetadataErrors() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <CreateItem Include='Foo' AdditionalMetadata='RecursiveDir=1'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.False(result); logger.AssertLogContains("MSB3031"); } /// <summary> /// Verify CreateItem prevents adding any built-in metadata explicitly, even recursivedir. /// </summary> [Fact] public void OtherBuiltInMetadataErrors2() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <CreateItem Include='Foo' AdditionalMetadata='Extension=1'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.False(result); logger.AssertLogContains("MSB3031"); } /// <summary> /// Verify that properties can be passed in to a task and out as items, despite the /// built-in metadata restrictions. /// </summary> [Fact] public void PropertiesInItemsOutOfTask() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <PropertyGroup> <p>c:\a.ext</p> </PropertyGroup> <CreateItem Include='$(p)'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> <Message Text='[%(x.Extension)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.True(result); logger.AssertLogContains("[.ext]"); } /// <summary> /// Verify that properties can be passed in to a task and out as items, despite /// having illegal characters for a file name /// </summary> [Fact] public void IllegalFileCharsInItemsOutOfTask() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <PropertyGroup> <p>||illegal||</p> </PropertyGroup> <CreateItem Include='$(p)'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> <Message Text='[@(x)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.True(result); logger.AssertLogContains("[||illegal||]"); } /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void NullMetadataOnOutputItems() { string customTaskPath = Assembly.GetExecutingAssembly().Location; string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <UsingTask TaskName=`NullMetadataTask` AssemblyFile=`" + customTaskPath + @"` /> <Target Name=`Build`> <NullMetadataTask> <Output TaskParameter=`OutputItems` ItemName=`Outputs`/> </NullMetadataTask> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogContains("[foo: ]"); } /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void NullMetadataOnLegacyOutputItems() { string customTaskPath = Assembly.GetExecutingAssembly().Location; string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <UsingTask TaskName=`NullMetadataTask` AssemblyFile=`" + customTaskPath + @"` /> <Target Name=`Build`> <NullMetadataTask> <Output TaskParameter=`OutputItems` ItemName=`Outputs`/> </NullMetadataTask> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogContains("[foo: ]"); } /// <summary> /// Regression test for https://github.com/microsoft/msbuild/issues/5080 /// </summary> [Fact] public void SameAssemblyFromDifferentRelativePathsSharesAssemblyLoadContext() { string realTaskPath = Assembly.GetExecutingAssembly().Location; string fileName = Path.GetFileName(realTaskPath); string directoryName = Path.GetDirectoryName(realTaskPath); using var env = TestEnvironment.Create(); string customTaskFolder = Path.Combine(directoryName, "buildCrossTargeting"); env.CreateFolder(customTaskFolder); string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <UsingTask TaskName=`RegisterObject` AssemblyFile=`" + Path.Combine(customTaskFolder, "..", fileName) + @"` /> <UsingTask TaskName=`RetrieveObject` AssemblyFile=`" + realTaskPath + @"` /> <Target Name=`Build`> <RegisterObject /> <RetrieveObject /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogDoesntContain("MSB4018"); } #if FEATURE_CODETASKFACTORY /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] public void NullMetadataOnOutputItems_InlineTask() { string projectContents = @" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`NullMetadataTask_v12` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <OutputItems ParameterType=`Microsoft.Build.Framework.ITaskItem[]` Output=`true` /> </ParameterGroup> <Task> <Code> <![CDATA[ OutputItems = new ITaskItem[1]; IDictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add(`a`, null); OutputItems[0] = new TaskItem(`foo`, (IDictionary)metadata); return true; ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <NullMetadataTask_v12> <Output TaskParameter=`OutputItems` ItemName=`Outputs` /> </NullMetadataTask_v12> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogContains("[foo: ]"); } /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] [Trait("Category", "non-mono-tests")] public void NullMetadataOnLegacyOutputItems_InlineTask() { string projectContents = @" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`NullMetadataTask_v4` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildFrameworkToolsPath)\Microsoft.Build.Tasks.v4.0.dll`> <ParameterGroup> <OutputItems ParameterType=`Microsoft.Build.Framework.ITaskItem[]` Output=`true` /> </ParameterGroup> <Task> <Code> <![CDATA[ OutputItems = new ITaskItem[1]; IDictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add(`a`, null); OutputItems[0] = new TaskItem(`foo`, (IDictionary)metadata); return true; ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <NullMetadataTask_v4> <Output TaskParameter=`OutputItems` ItemName=`Outputs` /> </NullMetadataTask_v4> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents, _testOutput); logger.AssertLogContains("[foo: ]"); } #endif /// <summary> /// Validates that the defining project metadata is set (or not set) as expected in /// various task output-related operations, using a task built against the current /// version of MSBuild. /// </summary> [Fact] public void ValidateDefiningProjectMetadataOnTaskOutputs() { string customTaskPath = Assembly.GetExecutingAssembly().Location; ValidateDefiningProjectMetadataOnTaskOutputsHelper(customTaskPath); } /// <summary> /// Validates that the defining project metadata is set (or not set) as expected in /// various task output-related operations, using a task built against V4 MSBuild, /// which didn't support the defining project metadata. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void ValidateDefiningProjectMetadataOnTaskOutputs_LegacyItems() { string customTaskPath = Assembly.GetExecutingAssembly().Location; ValidateDefiningProjectMetadataOnTaskOutputsHelper(customTaskPath); } #if FEATURE_APARTMENT_STATE /// <summary> /// Tests that putting the RunInSTA attribute on a task causes it to run in the STA thread. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadRequired() { TestSTATask(true, false, false); } /// <summary> /// Tests an STA task with an exception /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadRequiredWithException() { TestSTATask(true, false, true); } /// <summary> /// Tests an STA task with failure. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadRequiredWithFailure() { TestSTATask(true, true, false); } /// <summary> /// Tests an MTA task. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadNotRequired() { TestSTATask(false, false, false); } /// <summary> /// Tests an MTA task with an exception. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadNotRequiredWithException() { TestSTATask(false, false, true); } /// <summary> /// Tests an MTA task with failure. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadNotRequiredWithFailure() { TestSTATask(false, true, false); } #endif #region ITargetBuilderCallback Members /// <summary> /// Empty impl /// </summary> Task<ITargetResult[]> ITargetBuilderCallback.LegacyCallTarget(string[] targets, bool continueOnError, ElementLocation referenceLocation) { throw new NotImplementedException(); } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.Yield() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.Reacquire() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.EnterMSBuildCallbackState() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.ExitMSBuildCallbackState() { } #endregion #region IRequestBuilderCallback Members /// <summary> /// Empty impl /// </summary> Task<BuildResult[]> IRequestBuilderCallback.BuildProjects(string[] projectFiles, PropertyDictionary<ProjectPropertyInstance>[] properties, string[] toolsVersions, string[] targets, bool waitForResults, bool skipNonexistentTargets) { throw new NotImplementedException(); } /// <summary> /// Not implemented. /// </summary> Task IRequestBuilderCallback.BlockOnTargetInProgress(int blockingRequestId, string blockingTarget, BuildResult partialBuildResult) { throw new NotImplementedException(); } #endregion /********************************************************************************* * * Helpers * *********************************************************************************/ /// <summary> /// Helper method for validating the setting of defining project metadata on items /// coming from task outputs /// </summary> private void ValidateDefiningProjectMetadataOnTaskOutputsHelper(string customTaskPath) { string projectAPath = Path.Combine(ObjectModelHelpers.TempProjectDir, "a.proj"); string projectBPath = Path.Combine(ObjectModelHelpers.TempProjectDir, "b.proj"); string projectAContents = @" <Project xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`> <UsingTask TaskName=`ItemCreationTask` AssemblyFile=`" + customTaskPath + @"` /> <Import Project=`b.proj` /> <Target Name=`Run`> <ItemCreationTask InputItemsToPassThrough=`@(PassThrough)` InputItemsToCopy=`@(Copy)`> <Output TaskParameter=`OutputString` ItemName=`A` /> <Output TaskParameter=`PassedThroughOutputItems` ItemName=`B` /> <Output TaskParameter=`CreatedOutputItems` ItemName=`C` /> <Output TaskParameter=`CopiedOutputItems` ItemName=`D` /> </ItemCreationTask> <Warning Text=`A is wrong: EXPECTED: [a] ACTUAL: [%(A.DefiningProjectName)]` Condition=`'%(A.DefiningProjectName)' != 'a'` /> <Warning Text=`B is wrong: EXPECTED: [a] ACTUAL: [%(B.DefiningProjectName)]` Condition=`'%(B.DefiningProjectName)' != 'a'` /> <Warning Text=`C is wrong: EXPECTED: [a] ACTUAL: [%(C.DefiningProjectName)]` Condition=`'%(C.DefiningProjectName)' != 'a'` /> <Warning Text=`D is wrong: EXPECTED: [a] ACTUAL: [%(D.DefiningProjectName)]` Condition=`'%(D.DefiningProjectName)' != 'a'` /> </Target> </Project> "; string projectBContents = @" <Project xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`> <ItemGroup> <PassThrough Include=`aaa.cs` /> <Copy Include=`bbb.cs` /> </ItemGroup> </Project> "; try { File.WriteAllText(projectAPath, ObjectModelHelpers.CleanupFileContents(projectAContents)); File.WriteAllText(projectBPath, ObjectModelHelpers.CleanupFileContents(projectBContents)); MockLogger logger = new MockLogger(_testOutput); ObjectModelHelpers.BuildTempProjectFileExpectSuccess("a.proj", logger); logger.AssertNoWarnings(); } finally { if (File.Exists(projectAPath)) { File.Delete(projectAPath); } if (File.Exists(projectBPath)) { File.Delete(projectBPath); } } } #if FEATURE_APARTMENT_STATE /// <summary> /// Executes an STA task test. /// </summary> private void TestSTATask(bool requireSTA, bool failTask, bool throwException) { MockLogger logger = new MockLogger(); logger.AllowTaskCrashes = throwException; string taskAssemblyName; Project project = CreateSTATestProject(requireSTA, failTask, throwException, out taskAssemblyName); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); BuildParameters parameters = new BuildParameters(); parameters.Loggers = new ILogger[] { logger }; BuildResult result = BuildManager.DefaultBuildManager.Build(parameters, new BuildRequestData(project.CreateProjectInstance(), new string[] { "Foo" })); if (requireSTA) { logger.AssertLogContains("STA"); } else { logger.AssertLogContains("MTA"); } if (throwException) { logger.AssertLogContains("EXCEPTION"); Assert.Equal(BuildResultCode.Failure, result.OverallResult); return; } else { logger.AssertLogDoesntContain("EXCEPTION"); } if (failTask) { logger.AssertLogContains("FAIL"); Assert.Equal(BuildResultCode.Failure, result.OverallResult); } else { logger.AssertLogDoesntContain("FAIL"); } if (!throwException && !failTask) { Assert.Equal(BuildResultCode.Success, result.OverallResult); } } /// <summary> /// Helper to create a project which invokes the STA helper task. /// </summary> private Project CreateSTATestProject(bool requireSTA, bool failTask, bool throwException, out string assemblyToDelete) { assemblyToDelete = GenerateSTATask(requireSTA); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <UsingTask TaskName='ThreadTask' AssemblyFile='" + assemblyToDelete + @"'/> <Target Name='Foo'> <ThreadTask Fail='" + failTask + @"' ThrowException='" + throwException + @"'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); return project; } #endif /// <summary> /// Helper to create the STA test task. /// </summary> private string GenerateSTATask(bool requireSTA) { string taskContents = @" using System; using Microsoft.Build.Framework; namespace ClassLibrary2 {" + (requireSTA ? "[RunInSTA]" : String.Empty) + @" public class ThreadTask : ITask { #region ITask Members public IBuildEngine BuildEngine { get; set; } public bool ThrowException { get; set; } public bool Fail { get; set; } public bool Execute() { string message; if (System.Threading.Thread.CurrentThread.GetApartmentState() == System.Threading.ApartmentState.STA) { message = ""STA""; } else { message = ""MTA""; } BuildEngine.LogMessageEvent(new BuildMessageEventArgs(message, """", ""ThreadTask"", MessageImportance.High)); if (ThrowException) { throw new InvalidOperationException(""EXCEPTION""); } if (Fail) { BuildEngine.LogMessageEvent(new BuildMessageEventArgs(""FAIL"", """", ""ThreadTask"", MessageImportance.High)); } return !Fail; } public ITaskHost HostObject { get; set; } #endregion } }"; return CustomTaskHelper.GetAssemblyForTask(taskContents); } /// <summary> /// Creates a test project. /// </summary> /// <returns>The project.</returns> private ProjectInstance CreateTestProject() { string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <Compile Include='b.cs' /> <Compile Include='c.cs' /> </ItemGroup> <ItemGroup> <Reference Include='System' /> </ItemGroup> <Target Name='Empty' /> <Target Name='Skip' Inputs='testProject.proj' Outputs='testProject.proj' /> <Target Name='Error' > <ErrorTask1 ContinueOnError='True'/> <ErrorTask2 ContinueOnError='False'/> <ErrorTask3 /> <OnError ExecuteTargets='Foo'/> <OnError ExecuteTargets='Bar'/> </Target> <Target Name='Foo' Inputs='foo.cpp' Outputs='foo.o'> <FooTask1/> </Target> <Target Name='Bar'> <BarTask1/> </Target> <Target Name='Baz' DependsOnTargets='Bar'> <BazTask1/> <BazTask2/> </Target> <Target Name='Baz2' DependsOnTargets='Bar;Foo'> <Baz2Task1/> <Baz2Task2/> <Baz2Task3/> </Target> <Target Name='DepSkip' DependsOnTargets='Skip'> <DepSkipTask1/> <DepSkipTask2/> <DepSkipTask3/> </Target> <Target Name='DepError' DependsOnTargets='Foo;Skip;Error'> <DepSkipTask1/> <DepSkipTask2/> <DepSkipTask3/> </Target> </Project> "); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestConfiguration config = new BuildRequestConfiguration(1, new BuildRequestData("testfile", new Dictionary<string, string>(), "3.5", new string[0], null), "2.0"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); config.Project = project.CreateProjectInstance(); cache.AddConfiguration(config); return config.Project; } /// <summary> /// The mock component host object. /// </summary> private class MockHost : MockLoggingService, IBuildComponentHost, IBuildComponent { #region IBuildComponentHost Members /// <summary> /// The config cache /// </summary> private IConfigCache _configCache; /// <summary> /// The logging service /// </summary> private ILoggingService _loggingService; /// <summary> /// The results cache /// </summary> private IResultsCache _resultsCache; /// <summary> /// The request builder /// </summary> private IRequestBuilder _requestBuilder; /// <summary> /// The target builder /// </summary> private ITargetBuilder _targetBuilder; /// <summary> /// The build parameters. /// </summary> private BuildParameters _buildParameters; /// <summary> /// Retrieves the LegacyThreadingData associated with a particular component host /// </summary> private LegacyThreadingData _legacyThreadingData; private ISdkResolverService _sdkResolverService; /// <summary> /// Constructor /// /// UNDONE: Refactor this, and the other MockHosts, to use a common base implementation. The duplication of the /// logging implementation alone is unfortunate. /// </summary> public MockHost() { _buildParameters = new BuildParameters(); _legacyThreadingData = new LegacyThreadingData(); _configCache = new ConfigCache(); ((IBuildComponent)_configCache).InitializeComponent(this); _loggingService = this; _resultsCache = new ResultsCache(); ((IBuildComponent)_resultsCache).InitializeComponent(this); _requestBuilder = new RequestBuilder(); ((IBuildComponent)_requestBuilder).InitializeComponent(this); _targetBuilder = new TargetBuilder(); ((IBuildComponent)_targetBuilder).InitializeComponent(this); _sdkResolverService = new MockSdkResolverService(); ((IBuildComponent)_sdkResolverService).InitializeComponent(this); } /// <summary> /// Returns the node logging service. We don't distinguish here. /// </summary> public ILoggingService LoggingService { get { return _loggingService; } } /// <summary> /// Retrieves the name of the host. /// </summary> public string Name { get { return "TaskBuilder_Tests.MockHost"; } } /// <summary> /// Returns the build parameters. /// </summary> public BuildParameters BuildParameters { get { return _buildParameters; } } /// <summary> /// Retrieves the LegacyThreadingData associated with a particular component host /// </summary> LegacyThreadingData IBuildComponentHost.LegacyThreadingData { get { return _legacyThreadingData; } } /// <summary> /// Constructs and returns a component of the specified type. /// </summary> /// <param name="type">The type of component to return</param> /// <returns>The component</returns> public IBuildComponent GetComponent(BuildComponentType type) { return type switch { BuildComponentType.ConfigCache => (IBuildComponent)_configCache, BuildComponentType.LoggingService => (IBuildComponent)_loggingService, BuildComponentType.ResultsCache => (IBuildComponent)_resultsCache, BuildComponentType.RequestBuilder => (IBuildComponent)_requestBuilder, BuildComponentType.TargetBuilder => (IBuildComponent)_targetBuilder, BuildComponentType.SdkResolverService => (IBuildComponent)_sdkResolverService, _ => throw new ArgumentException("Unexpected type " + type), }; } /// <summary> /// Register a component factory. /// </summary> public void RegisterFactory(BuildComponentType type, BuildComponentFactoryDelegate factory) { } #endregion #region IBuildComponent Members /// <summary> /// Sets the component host /// </summary> /// <param name="host">The component host</param> public void InitializeComponent(IBuildComponentHost host) { throw new NotImplementedException(); } /// <summary> /// Shuts down the component /// </summary> public void ShutdownComponent() { throw new NotImplementedException(); } #endregion } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: Contains the business logic for symbology layers and symbol categories. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 4/9/2009 3:42:59 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Xml.Serialization; using DotSpatial.Data; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// Represents a cartographic stroke with several useful settings. /// </summary> [Serializable, XmlRoot("CartographicStroke")] public class CartographicStroke : SimpleStroke, ICartographicStroke { #region Private Variables private float[] _compondArray; private bool[] _compoundButtons; private bool[] _dashButtons; private DashCap _dashCap; private float[] _dashPattern; private IList<ILineDecoration> _decorations; private LineCap _endCap; private LineJoinType _joinType; private float _offset; private LineCap _startCap; #endregion #region Constructors /// <summary> /// Creates a new instance of CartographicStroke /// </summary> public CartographicStroke() { Color = SymbologyGlobal.RandomDarkColor(1); Configure(); } /// <summary> /// Getnerates a cartographic stroke of the specified color /// </summary> /// <param name="color"></param> public CartographicStroke(Color color) { Color = color; Configure(); } private void Configure() { _joinType = LineJoinType.Round; _startCap = LineCap.Round; _endCap = LineCap.Round; _decorations = new CopyList<ILineDecoration>(); } #endregion #region Methods /// <summary> /// Creates a pen for drawing the non-decorative portion of the line. /// </summary> ///<param name="scaleWidth">The base width in pixels that is equivalent to a width of 1</param> /// <returns>A new Pen</returns> public override Pen ToPen(double scaleWidth) { Pen myPen = base.ToPen(scaleWidth); myPen.EndCap = _endCap; myPen.StartCap = _startCap; if (_compondArray != null) myPen.CompoundArray = _compondArray; if (_offset != 0F) { float[] pattern = new float[] { 0, 1 }; float w = (float)Width; if (w == 0) w = 1; w = (float)(scaleWidth * w); float w2 = (Math.Abs(_offset) + w / 2) * 2; if (_compondArray != null) { pattern = new float[_compondArray.Length]; for (int i = 0; i < _compondArray.Length; i++) { pattern[i] = _compondArray[i]; } } for (int i = 0; i < pattern.Length; i++) { if (_offset > 0) { pattern[i] = (w / w2) * pattern[i]; } else { pattern[i] = 1 - (w / w2) + (w / w2) * pattern[i]; } } myPen.CompoundArray = pattern; myPen.Width = w2; } if (_dashPattern != null) { myPen.DashPattern = _dashPattern; } else { if (myPen.DashStyle == DashStyle.Custom) { myPen.DashStyle = DashStyle.Solid; } } switch (_joinType) { case LineJoinType.Bevel: myPen.LineJoin = LineJoin.Bevel; break; case LineJoinType.Mitre: myPen.LineJoin = LineJoin.Miter; break; case LineJoinType.Round: myPen.LineJoin = LineJoin.Round; break; } return myPen; } /// <summary> /// Draws the line with max. 2 decorations. Otherwise the legend line might show only decorations. /// </summary> /// <param name="g"></param> /// <param name="path"></param> /// <param name="scaleWidth"></param> public void DrawLegendPath(Graphics g, GraphicsPath path, double scaleWidth) { base.DrawPath(g, path, scaleWidth); // draw the actual line if (Decorations != null) { int temp = -1; foreach (ILineDecoration decoration in Decorations) { if (decoration.NumSymbols > 2) { temp = decoration.NumSymbols; decoration.NumSymbols = 2; } decoration.Draw(g, path, scaleWidth); if (temp > -1) { decoration.NumSymbols = temp; temp = -1; } } } } /// <summary> /// Draws the actual path, overriding the base behavior to include markers. /// </summary> /// <param name="g"></param> /// <param name="path"></param> /// <param name="scaleWidth"></param> public override void DrawPath(Graphics g, GraphicsPath path, double scaleWidth) { base.DrawPath(g, path, scaleWidth); // draw the actual line if (Decorations != null) { foreach (ILineDecoration decoration in Decorations) { decoration.Draw(g, path, scaleWidth); } } } /// <summary> /// Gets the width and height that is needed to draw this stroke with max. 2 decorations. /// </summary> public Size GetLegendSymbolSize() { Size size = new Size(16, 16); foreach (ILineDecoration decoration in Decorations) { Size s = decoration.GetLegendSymbolSize(); if (s.Height > size.Height) size.Height = s.Height; if (s.Width > size.Width) size.Width = s.Width; } return size; } #endregion #region Properties /// <summary> /// Gets or sets an array of floating point values ranging from 0 to 1 that /// indicate the start and end point for where the line should draw. /// </summary> [XmlIgnore] public float[] CompoundArray { get { return _compondArray; } set { _compondArray = value; } } /// <summary> /// gets or sets the DashCap for both the start and end caps of the dashes /// </summary> [Serialize("DashCap")] public DashCap DashCap { get { return _dashCap; } set { _dashCap = value; } } /// <summary> /// Gets or sets the DashPattern as an array of floating point values from 0 to 1 /// </summary> [XmlIgnore] public float[] DashPattern { get { return _dashPattern; } set { _dashPattern = value; } } /// <summary> /// Gets or sets the line decoration that describes symbols that should /// be drawn along the line as decoration. /// </summary> [Serialize("Decorations")] public IList<ILineDecoration> Decorations { get { return _decorations; } set { _decorations = value; } } /// <summary> /// Gets or sets the line cap for both the start and end of the line /// </summary> [Serialize("EndCap")] public LineCap EndCap { get { return _endCap; } set { _endCap = value; } } /// <summary> /// Gets or sets the OGC line characteristic that controls how connected segments /// are drawn where they come together. /// </summary> [Serialize("JoinType")] public LineJoinType JoinType { get { return _joinType; } set { _joinType = value; } } /// <summary> /// Gets or sets the line cap for both the start and end of the line /// </summary> [Serialize("LineCap")] public LineCap StartCap { get { return _startCap; } set { _startCap = value; } } /// <summary> /// This is a cached version of the horizontal pattern that should appear in the custom dash control. /// This is only used if DashStyle is set to custom, and only controls the pattern control, /// and does not directly affect the drawing pen. /// </summary> public bool[] DashButtons { get { return _dashButtons; } set { _dashButtons = value; } } /// <summary> /// This is a cached version of the vertical pattern that should appear in the custom dash control. /// This is only used if DashStyle is set to custom, and only controls the pattern control, /// and does not directly affect the drawing pen. /// </summary> public bool[] CompoundButtons { get { return _compoundButtons; } set { _compoundButtons = value; } } /// <summary> /// Gets or sets the floating poing offset (in pixels) for the line to be drawn to the left of /// the original line. (Internally, this will modify the width and compound array for the /// actual pen being used, as Pens do not support an offset property). /// </summary> [Serialize("Offset")] public float Offset { get { return _offset; } set { _offset = value; } } #endregion #region Protected Methods /// <summary> /// Handles the randomization of the cartographic properties of this stroke. /// </summary> /// <param name="generator">The random class that generates the random numbers</param> protected override void OnRandomize(Random generator) { base.OnRandomize(generator); DashStyle = DashStyle.Custom; _dashCap = generator.NextEnum<DashCap>(); _startCap = generator.NextEnum<LineCap>(); _endCap = generator.NextEnum<LineCap>(); _dashButtons = generator.NextBoolArray(1, 20); _compoundButtons = generator.NextBoolArray(1, 5); _offset = generator.NextFloat(10); _joinType = generator.NextEnum<LineJoinType>(); int len = generator.Next(0, 1); if (len > 0) { _decorations.Clear(); LineDecoration ld = new LineDecoration(); ld.Randomize(generator); _decorations.Add(ld); } } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record.CF { using System; using System.Text; using NPOI.HSSF.Record; using NPOI.Util; using NPOI.SS.UserModel; /** * Font Formatting Block of the Conditional Formatting Rule Record. * * @author Dmitriy Kumshayev */ public class FontFormatting : ICloneable { private byte[] _rawData = new byte[RAW_DATA_SIZE]; private const int OFFSET_FONT_NAME = 0; private const int OFFSET_FONT_HEIGHT = 64; private const int OFFSET_FONT_OPTIONS = 68; private const int OFFSET_FONT_WEIGHT = 72; private const int OFFSET_ESCAPEMENT_TYPE = 74; private const int OFFSET_UNDERLINE_TYPE = 76; private const int OFFSET_FONT_COLOR_INDEX = 80; private const int OFFSET_OPTION_FLAGS = 88; private const int OFFSET_ESCAPEMENT_TYPE_MODIFIED = 92; private const int OFFSET_UNDERLINE_TYPE_MODIFIED = 96; private const int OFFSET_FONT_WEIGHT_MODIFIED = 100; private const int OFFSET_NOT_USED1 = 104; private const int OFFSET_NOT_USED2 = 108; private const int OFFSET_NOT_USED3 = 112; // for some reason Excel always Writes 0x7FFFFFFF at this offset private const int OFFSET_FONT_FORMATING_END = 116; private const int RAW_DATA_SIZE = 118; public const int FONT_CELL_HEIGHT_PRESERVED = unchecked((int)0xFFFFFFFF); // FONT OPTIONS MASKS private static BitField posture = BitFieldFactory.GetInstance(0x00000002); private static BitField outline = BitFieldFactory.GetInstance(0x00000008); private static BitField shadow = BitFieldFactory.GetInstance(0x00000010); private static BitField cancellation = BitFieldFactory.GetInstance(0x00000080); // OPTION FLAGS MASKS private static BitField styleModified = BitFieldFactory.GetInstance(0x00000002); private static BitField outlineModified = BitFieldFactory.GetInstance(0x00000008); private static BitField shadowModified = BitFieldFactory.GetInstance(0x00000010); private static BitField cancellationModified = BitFieldFactory.GetInstance(0x00000080); /** Normal boldness (not bold) */ private const short FONT_WEIGHT_NORMAL = 0x190; /** * Bold boldness (bold) */ private const short FONT_WEIGHT_BOLD = 0x2bc; public FontFormatting() { FontHeight=-1; IsItalic=false; IsFontWeightModified=false; IsOutlineOn=false; IsShadowOn=false; IsStruckout=false; EscapementType=(FontSuperScript)0; UnderlineType=(FontUnderlineType)0; FontColorIndex=(short)-1; IsFontStyleModified=false; IsFontOutlineModified=false; IsFontShadowModified=false; IsFontCancellationModified=false; IsEscapementTypeModified=false; IsUnderlineTypeModified=false; SetShort(OFFSET_FONT_NAME, 0); SetInt(OFFSET_NOT_USED1, 0x00000001); SetInt(OFFSET_NOT_USED2, 0x00000000); SetInt(OFFSET_NOT_USED3, 0x7FFFFFFF);// for some reason Excel always Writes 0x7FFFFFFF at this offset SetShort(OFFSET_FONT_FORMATING_END, 0x0001); } /** Creates new FontFormatting */ public FontFormatting(RecordInputStream in1) { for (int i = 0; i < _rawData.Length; i++) { _rawData[i] =(byte) in1.ReadByte(); } } private short GetShort(int offset) { return LittleEndian.GetShort(_rawData, offset); } private void SetShort(int offset, int value) { LittleEndian.PutShort(_rawData, offset, (short)value); } private int GetInt(int offset) { return LittleEndian.GetInt(_rawData, offset); } private void SetInt(int offset, int value) { LittleEndian.PutInt(_rawData, offset, value); } public byte[] RawRecord { get { return _rawData; } } public int DataLength { get { return RAW_DATA_SIZE; } } /** * Gets the height of the font in 1/20th point Units * * @return fontheight (in points/20); or -1 if not modified */ public int FontHeight { get{return GetInt(OFFSET_FONT_HEIGHT);} set { SetInt(OFFSET_FONT_HEIGHT, value); } } private void SetFontOption(bool option, BitField field) { int options = GetInt(OFFSET_FONT_OPTIONS); options = field.SetBoolean(options, option); SetInt(OFFSET_FONT_OPTIONS, options); } private bool GetFontOption(BitField field) { int options = GetInt(OFFSET_FONT_OPTIONS); return field.IsSet(options); } /** * Get whether the font Is to be italics or not * * @return italics - whether the font Is italics or not * @see #GetAttributes() */ public bool IsItalic { get { return GetFontOption(posture); } set { SetFontOption(value, posture); } } public bool IsOutlineOn { get { return GetFontOption(outline); } set { SetFontOption(value, outline); } } public bool IsShadowOn { get { return GetFontOption(shadow); } set { SetFontOption(value, shadow); } } /** * Get whether the font Is to be stricken out or not * * @return strike - whether the font Is stricken out or not * @see #GetAttributes() */ public bool IsStruckout { get { return GetFontOption(cancellation); } set { SetFontOption(value, cancellation); } } /// <summary> /// Get or set the font weight for this font (100-1000dec or 0x64-0x3e8). /// Default Is 0x190 for normal and 0x2bc for bold /// </summary> public short FontWeight { get { return GetShort(OFFSET_FONT_WEIGHT); } set { short bw = value; if (bw < 100) { bw = 100; } if (bw > 1000) { bw = 1000; } SetShort(OFFSET_FONT_WEIGHT, bw); } } /// <summary> ///Get or set whether the font weight is set to bold or not /// </summary> public bool IsBold { get { return FontWeight == FONT_WEIGHT_BOLD; } set { this.FontWeight = (value ? FONT_WEIGHT_BOLD : FONT_WEIGHT_NORMAL); } } /** * Get the type of base or subscript for the font * * @return base or subscript option * @see org.apache.poi.hssf.usermodel.HSSFFontFormatting#SS_NONE * @see org.apache.poi.hssf.usermodel.HSSFFontFormatting#SS_SUPER * @see org.apache.poi.hssf.usermodel.HSSFFontFormatting#SS_SUB */ public FontSuperScript EscapementType { get { return (FontSuperScript)GetShort(OFFSET_ESCAPEMENT_TYPE); } set { SetShort(OFFSET_ESCAPEMENT_TYPE, (short)value); } } /** * Get the type of Underlining for the font * * @return font Underlining type */ public FontUnderlineType UnderlineType { get { return (FontUnderlineType)GetShort(OFFSET_UNDERLINE_TYPE); } set { SetShort(OFFSET_UNDERLINE_TYPE, (short)value); } } public short FontColorIndex { get { return (short)GetInt(OFFSET_FONT_COLOR_INDEX); } set { SetInt(OFFSET_FONT_COLOR_INDEX, value); } } private bool GetOptionFlag(BitField field) { int optionFlags = GetInt(OFFSET_OPTION_FLAGS); int value = field.GetValue(optionFlags); return value == 0 ? true : false; } private void SetOptionFlag(bool modified, BitField field) { int value = modified ? 0 : 1; int optionFlags = GetInt(OFFSET_OPTION_FLAGS); optionFlags = field.SetValue(optionFlags, value); SetInt(OFFSET_OPTION_FLAGS, optionFlags); } public bool IsFontStyleModified { get { return GetOptionFlag(styleModified); } set { SetOptionFlag(value, styleModified); } } public bool IsFontOutlineModified { get { return GetOptionFlag(outlineModified); } set { SetOptionFlag(value, outlineModified); } } public bool IsFontShadowModified { get { return GetOptionFlag(shadowModified); } set { SetOptionFlag(value, shadowModified); } } public bool IsFontCancellationModified { get { return GetOptionFlag(cancellationModified); } set { SetOptionFlag(value, cancellationModified); } } public bool IsEscapementTypeModified { get { int escapementModified = GetInt(OFFSET_ESCAPEMENT_TYPE_MODIFIED); return escapementModified == 0; } set { int value1 = value ? 0 : 1; SetInt(OFFSET_ESCAPEMENT_TYPE_MODIFIED, value1); } } public bool IsUnderlineTypeModified { get { int underlineModified = GetInt(OFFSET_UNDERLINE_TYPE_MODIFIED); return underlineModified == 0; } set { int value1 = value ? 0 : 1; SetInt(OFFSET_UNDERLINE_TYPE_MODIFIED, value1); } } public bool IsFontWeightModified { get { int fontStyleModified = GetInt(OFFSET_FONT_WEIGHT_MODIFIED); return fontStyleModified == 0; } set { int value1 = value ? 0 : 1; SetInt(OFFSET_FONT_WEIGHT_MODIFIED, value1); } } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append(" [Font Formatting]\n"); buffer.Append(" .font height = ").Append(FontHeight).Append(" twips\n"); if (IsFontStyleModified) { buffer.Append(" .font posture = ").Append(IsItalic ? "Italic" : "Normal").Append("\n"); } else { buffer.Append(" .font posture = ]not modified]").Append("\n"); } if (IsFontOutlineModified) { buffer.Append(" .font outline = ").Append(IsOutlineOn).Append("\n"); } else { buffer.Append(" .font outline Is not modified\n"); } if (IsFontShadowModified) { buffer.Append(" .font shadow = ").Append(IsShadowOn).Append("\n"); } else { buffer.Append(" .font shadow Is not modified\n"); } if (IsFontCancellationModified) { buffer.Append(" .font strikeout = ").Append(IsStruckout).Append("\n"); } else { buffer.Append(" .font strikeout Is not modified\n"); } if (IsFontStyleModified) { buffer.Append(" .font weight = "). Append(FontWeight). Append( FontWeight == FONT_WEIGHT_NORMAL ? "(Normal)" : FontWeight == FONT_WEIGHT_BOLD ? "(Bold)" : "0x" + StringUtil.ToHexString(FontWeight)). Append("\n"); } else { buffer.Append(" .font weight = ]not modified]").Append("\n"); } if (IsEscapementTypeModified) { buffer.Append(" .escapement type = ").Append(EscapementType).Append("\n"); } else { buffer.Append(" .escapement type Is not modified\n"); } if (IsUnderlineTypeModified) { buffer.Append(" .underline type = ").Append(UnderlineType).Append("\n"); } else { buffer.Append(" .underline type Is not modified\n"); } buffer.Append(" .color index = ").Append("0x" + StringUtil.ToHexString(FontColorIndex).ToUpper()).Append("\n"); buffer.Append(" [/Font Formatting]\n"); return buffer.ToString(); } public Object Clone() { FontFormatting other = new FontFormatting(); Array.Copy(_rawData, 0, other._rawData, 0, _rawData.Length); return other; } } }
/* * INI files. * * Copyright by Gajatko a.d. 2007. * All rights reserved. * * In this file there are all needed classes to parse, manage and write old-style * INI [=initialization] files, like "win.ini" in Windows folder. * However, they use classes contained in the "ConfigFileElement.cs" source file. */ using System; using System.Collections.Generic; using System.Text; using System.IO; namespace C0DEC0RE { /// <summary>StreamReader implementation, which read from an INI file. /// IniFileReader DOES NOT override any StreamReader methods. New ones are added.</summary> public class IniFileReader : StreamReader { /// <summary>Initializes a new instance of IniFileReader from specified stream.</summary> public IniFileReader(Stream str) : base(str) { } /// <summary>Initializes a new instance of IniFileReader from specified stream and encoding.</summary> public IniFileReader(Stream str, Encoding enc) : base(str, enc) { } /// <summary>Initializes a new instance of IniFileReader from specified path.</summary> public IniFileReader(string path) : base(path) { } /// <summary>Initializes a new instance of IniFileReader from specified path and encoding.</summary> public IniFileReader(string path, Encoding enc) : base(path, enc) { } IniFileElement current = null; /// <summary>Parses a single line.</summary> /// <param name="line">Text to parse.</param> public static IniFileElement ParseLine(string line) { if (line == null) return null; if (line.Contains("\n")) throw new ArgumentException("String passed to the ParseLine method cannot contain more than one line."); string trim = line.Trim(); IniFileElement elem = null; if (IniFileBlankLine.IsLineValid(trim)) elem = new IniFileBlankLine(1); else if (IniFileCommentary.IsLineValid(line)) elem = new IniFileCommentary(line); else if (IniFileSectionStart.IsLineValid(trim)) elem = new IniFileSectionStart(line); else if (IniFileValue.IsLineValid(trim)) elem = new IniFileValue(line); return elem ?? new IniFileElement(line); } /// <summary>Parses given text.</summary> /// <param name="text">Text to parse.</param> public static List<IniFileElement> ParseText(string text) { if (text == null) return null; List<IniFileElement> ret = new List<IniFileElement>(); IniFileElement currEl, lastEl = null; string[] lines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); for (int i = 0; i < lines.Length; i++) { currEl = ParseLine(lines[i]); if (IniFileSettings.GroupElements) { if (lastEl != null) { if (currEl is IniFileBlankLine && lastEl is IniFileBlankLine) { ((IniFileBlankLine)lastEl).Amount++; continue; } else if (currEl is IniFileCommentary && lastEl is IniFileCommentary) { ((IniFileCommentary)lastEl).Comment += Environment.NewLine + ((IniFileCommentary)currEl).Comment; continue; } } else lastEl = currEl; } lastEl = currEl; ret.Add(currEl); } return ret; } /// <summary>Reads and parses next line from the config file.</summary> /// <returns>Created ConfigFileElement.</returns> public IniFileElement ReadElement() { current = ParseLine(base.ReadLine()); return current; } /// <summary>Reads all files</summary> /// <returns>All new elements which was added.</returns> public List<IniFileElement> ReadElementsToEnd() { List<IniFileElement> ret = ParseText(base.ReadToEnd()); return ret; } /// <summary>Seeks to the section of specified name. If such section is not found, /// the function returns NULL and leaves the stream at the end of file.</summary> /// <param name="sectionName">Name of section to find.</param> public IniFileSectionStart GotoSection(string sectionName) { IniFileSectionStart sect = null; string str; while (true) { str = ReadLine(); if (str == null) { current = null; return null; } if (IniFileSectionStart.IsLineValid(str)) { sect = ParseLine(str) as IniFileSectionStart; if (sect != null && (sect.SectionName == sectionName || (!IniFileSettings.CaseSensitive && sect.SectionName.ToLowerInvariant() == sectionName))) { current = sect; return sect; } } } } /// <summary>Returns a list of IniFileElement object in the currect section. The first element of /// returned collection will be a IniFileSectionStart.</summary> /// <exception cref="System.InvalidOperationException">A stream is not currently at the IniFileSectionStart.</exception> public List<IniFileElement> ReadSection() { if (current == null || !(current is IniFileSectionStart)) throw new InvalidOperationException("The current position of the reader must be at IniFileSectionStart. Use GotoSection method"); List<IniFileElement> ret = new List<IniFileElement>(); IniFileElement theCurrent = current; ret.Add(theCurrent); string text = "", temp; while ((temp = base.ReadLine()) != null) { if (IniFileSectionStart.IsLineValid(temp.Trim())) { current = new IniFileSectionStart(temp); break; } text += temp + Environment.NewLine; } if (text.EndsWith(Environment.NewLine) && text != Environment.NewLine) text = text.Substring(0, text.Length - Environment.NewLine.Length); ret.AddRange(ParseText(text)); return ret; } /// <summary>Gets a recently parsed IniFileElement.</summary> public IniFileElement Current { get { return current; } } /// <summary>Gets values of the current section.</summary> /// <exception cref="System.InvalidOperationException">A stream is not currently at the IniFileSectionStart.</exception> public List<IniFileValue> ReadSectionValues() { List<IniFileElement> elements = ReadSection(); List<IniFileValue> ret = new List<IniFileValue>(); for (int i = 0; i < elements.Count; i++) if (elements[i] is IniFileValue) ret.Add((IniFileValue)elements[i]); return ret; } /// <summary>Searches the current section for a value of specified key. If such key is not found, /// the function returns NULL and leaves the stream at next section.</summary> /// <param name="key">Key to find.</param> public IniFileValue GotoValue(string key) { return GotoValue(key, false); } /// <summary>Searches for a value of specified key. If such key is not found, /// the function returns NULL and leaves the stream at next section.</summary> /// <param name="key">Key to find.</param> /// <param name="searchWholeFile">Sets a search scope. If true, function will not stop at the next IniFileSectionStart.</param> public IniFileValue GotoValue(string key, bool searchWholeFile) { IniFileValue val; string str; while (true) { str = ReadLine(); if (str == null) return null; if (IniFileValue.IsLineValid(str.Trim())) { val = ParseLine(str) as IniFileValue; if (val != null && (val.Key == key || (!IniFileSettings.CaseSensitive && val.Key.ToLowerInvariant() == key.ToLowerInvariant()))) return val; } if (!searchWholeFile && IniFileSectionStart.IsLineValid(str.Trim())) return null; } } } /// <summary>StreamWriter implementation which writes an INI file. /// IniFileWriter DOES NOT override any StreamReader methods. New ones are added.</summary> public class IniFileWriter : StreamWriter { /// <summary>Initializes a new instance of IniFileReader from specified stream.</summary> public IniFileWriter(Stream str) : base(str) { } /// <summary>Initializes a new instance of IniFileReader from specified path.</summary> public IniFileWriter(string str) : base(str) { } /// <summary>Initializes a new instance of IniFileReader from specified stream and encoding.</summary> public IniFileWriter(Stream str, Encoding enc) : base(str, enc) { } /// <summary>Initializes a new instance of IniFileReader from specified path and encoding.</summary> public IniFileWriter(string str, bool append) : base(str, append) { } /// <summary>Writes INI file element to the file.</summary> /// <param name="element">Element to write.</param> public void WriteElement(IniFileElement element) { if (!IniFileSettings.PreserveFormatting) element.FormatDefault(); // do not write if: if (!( // 1) element is a blank line AND blank lines are not allowed (element is IniFileBlankLine && !IniFileSettings.AllowBlankLines) // 2) element is an empty value AND empty values are not allowed || (!IniFileSettings.AllowEmptyValues && element is IniFileValue && ((IniFileValue)element).Value == ""))) base.WriteLine(element.Line); } /// <summary>Writes collection of INI file elements to the file.</summary> /// <param name="elements">Elements collection to write.</param> public void WriteElements(IEnumerable<IniFileElement> elements) { lock (elements) foreach (IniFileElement el in elements) WriteElement(el); } /// <summary>Writes a whole INI to a file</summary> /// <param name="file">Section to write.</param> public void WriteIniFile(IniFile file) { WriteElements(file.elements); } /// <summary>Writes a section to a file</summary> /// <param name="section">Section to write.</param> public void WriteSection(IniFileSection section) { WriteElement(section.sectionStart); for (int i = section.parent.elements.IndexOf(section.sectionStart) + 1; i < section.parent.elements.Count; i++) { if (section.parent.elements[i] is IniFileSectionStart) break; WriteElement(section.parent.elements[i]); } } } /// <summary>Object model for INI file, which stores a whole structure in memory.</summary> public class IniFile { internal List<IniFileSection> sections = new List<IniFileSection>(); internal List<IniFileElement> elements = new List<IniFileElement>(); /// <summary>Creates new instance of IniFile.</summary> public IniFile() { } /// <summary>Gets a IniFileSection object from it's name</summary> /// <param name="sectionName">Name of section to search for. If not found, new one is created.</param> public IniFileSection this[string sectionName] { get { IniFileSection sect = getSection(sectionName); if (sect != null) return sect; IniFileSectionStart start; if (sections.Count > 0) { IniFileSectionStart prev = sections[sections.Count - 1].sectionStart; start = prev.CreateNew(sectionName); } else start = IniFileSectionStart.FromName(sectionName); elements.Add(start); sect = new IniFileSection(this, start); sections.Add(sect); return sect; } } IniFileSection getSection(string name) { string lower = name.ToLowerInvariant(); for (int i = 0; i < sections.Count; i++) if (sections[i].Name == name || (!IniFileSettings.CaseSensitive && sections[i].Name.ToLowerInvariant() == lower)) return sections[i]; return null; } /// <summary>Gets an array of names of sections in this INI file.</summary> public string[] GetSectionNames() { string[] ret = new string[sections.Count]; for (int i = 0; i < sections.Count; i++) ret[i] = sections[i].Name; return ret; } /// <summary>Reads a INI file from a file or creates one.</summary> public static IniFile FromFile(string path) { if (!System.IO.File.Exists(path)) { System.IO.File.Create(path).Close(); return new IniFile(); } IniFileReader reader = new IniFileReader(path); IniFile ret = FromStream(reader); reader.Close(); return ret; } /// <summary>Creates a new IniFile from elements collection (Advanced member).</summary> /// <param name="elemes">Elements collection.</param> public static IniFile FromElements(IEnumerable<IniFileElement> elemes) { IniFile ret = new IniFile(); ret.elements.AddRange(elemes); if (ret.elements.Count > 0) { IniFileSection section = null; IniFileElement el; if (ret.elements[ret.elements.Count - 1] is IniFileBlankLine) ret.elements.RemoveAt(ret.elements.Count - 1); for (int i = 0; i < ret.elements.Count; i++) { el = ret.elements[i]; if (el is IniFileSectionStart) { section = new IniFileSection(ret, (IniFileSectionStart)el); ret.sections.Add(section); } else if (section != null) section.elements.Add(el); else if (ret.sections.Exists(delegate(IniFileSection a) { return a.Name == ""; })) ret.sections[0].elements.Add(el); else if (el is IniFileValue) { section = new IniFileSection(ret, IniFileSectionStart.FromName("")); section.elements.Add(el); ret.sections.Add(section); } } } return ret; } /// <summary>Reads a INI file from a stream.</summary> public static IniFile FromStream(IniFileReader reader) { return FromElements(reader.ReadElementsToEnd()); } /// <summary>Writes a INI file to a disc, using options in IniFileSettings class</summary> public void Save(string path) { IniFileWriter writer = new IniFileWriter(path); Save(writer); writer.Close(); } /// <summary>Writes a INI file to a stream, using options in IniFileSettings class</summary> public void Save(IniFileWriter writer) { writer.WriteIniFile(this); } /// <summary>Deletes a section and all it's values and comments. No exception is thrown if there is no section of requested name.</summary> /// <param name="name">Name of section to delete.</param> public void DeleteSection(string name) { IniFileSection section = getSection(name); if (section == null) return; IniFileSectionStart sect = section.sectionStart; elements.Remove(sect); for (int i = elements.IndexOf(sect) + 1; i < elements.Count; i++) { if (elements[i] is IniFileSectionStart) break; elements.RemoveAt(i); } } /// <summary>Formats whole INI file.</summary> /// <param name="preserveIntendation">If true, old intendation will be standarized but not removed.</param> public void Format(bool preserveIntendation) { string lastSectIntend = ""; string lastValIntend = ""; IniFileElement el; for (int i = 0; i < elements.Count; i++) { el = elements[i]; if (preserveIntendation) { if (el is IniFileSectionStart) lastValIntend = lastSectIntend = el.Intendation; else if (el is IniFileValue) lastValIntend = el.Intendation; } el.FormatDefault(); if (preserveIntendation) { if (el is IniFileSectionStart) el.Intendation = lastSectIntend; else if (el is IniFileCommentary && i != elements.Count - 1 && !(elements[i + 1] is IniFileBlankLine)) el.Intendation = elements[i + 1].Intendation; else el.Intendation = lastValIntend; } } } /// <summary>Joins sections which are definied more than one time.</summary> public void UnifySections() { Dictionary<string, int> dict = new Dictionary<string, int>(); IniFileSection sect; IniFileElement el; IniFileValue val; int index; for (int i = 0; i < sections.Count; i++) { sect = sections[i]; if (dict.ContainsKey(sect.Name)) { index = dict[sect.Name] + 1; elements.Remove(sect.sectionStart); sections.Remove(sect); for (int j = sect.elements.Count - 1; j >= 0; j--) { el = sect.elements[j]; if (!(j == sect.elements.Count - 1 && el is IniFileCommentary)) elements.Remove(el); if (!(el is IniFileBlankLine)) { elements.Insert(index, el); val = this[sect.Name].firstValue(); if (val != null) el.Intendation = val.Intendation; else el.Intendation = this[sect.Name].sectionStart.Intendation; } } } else dict.Add(sect.Name, elements.IndexOf(sect.sectionStart)); } } /// <summary>Gets or sets a header commentary of an INI file. Header comment must if separate from /// comment of a first section except when IniFileSetting.SeparateHeader is set to false.</summary> public string Header { get { if (elements.Count > 0) if (elements[0] is IniFileCommentary && !(!IniFileSettings.SeparateHeader && elements.Count > 1 && !(elements[1] is IniFileBlankLine))) return ((IniFileCommentary)elements[0]).Comment; return ""; } set { if (elements.Count > 0 && elements[0] is IniFileCommentary && !(!IniFileSettings.SeparateHeader && elements.Count > 1 && !(elements[1] is IniFileBlankLine))) { if (value == "") { elements.RemoveAt(0); if (IniFileSettings.SeparateHeader && elements.Count > 0 && elements[0] is IniFileBlankLine) elements.RemoveAt(0); } else ((IniFileCommentary)elements[0]).Comment = value; } else if (value != "") { if ((elements.Count == 0 || !(elements[0] is IniFileBlankLine)) && IniFileSettings.SeparateHeader) elements.Insert(0, new IniFileBlankLine(1)); elements.Insert(0, IniFileCommentary.FromComment(value)); } } } /// <summary>Gets or sets a commentary at the end of an INI file.</summary> public string Foot { get { if (elements.Count > 0) { if (elements[elements.Count - 1] is IniFileCommentary) return ((IniFileCommentary)elements[elements.Count - 1]).Comment; } return ""; } set { if (value == "") { if (elements.Count > 0 && elements[elements.Count - 1] is IniFileCommentary) { elements.RemoveAt(elements.Count - 1); if (elements.Count > 0 && elements[elements.Count - 1] is IniFileBlankLine) elements.RemoveAt(elements.Count - 1); } } else { if (elements.Count > 0) { if (elements[elements.Count - 1] is IniFileCommentary) ((IniFileCommentary)elements[elements.Count - 1]).Comment = value; else elements.Add(IniFileCommentary.FromComment(value)); if (elements.Count > 2) { if (!(elements[elements.Count - 2] is IniFileBlankLine) && IniFileSettings.SeparateHeader) elements.Insert(elements.Count - 1, new IniFileBlankLine(1)); else if (value == "") elements.RemoveAt(elements.Count - 2); } } else elements.Add(IniFileCommentary.FromComment(value)); } } } } /// <summary>Object model for a section in an INI file, which stores a all values in memory.</summary> public class IniFileSection { internal List<IniFileElement> elements = new List<IniFileElement>(); internal IniFileSectionStart sectionStart; internal IniFile parent; internal IniFileSection(IniFile _parent, IniFileSectionStart sect) { sectionStart = sect; parent = _parent; } /// <summary>Gets or sets the name of the section</summary> public string Name { get { return sectionStart.SectionName; } set { sectionStart.SectionName = value; } } /// <summary>Gets or sets comment associated with this section. In the file a comment must appear exactly /// above section's declaration. Returns "" if no comment is provided.</summary> public string Comment { get { return Name == "" ? "" : getComment(sectionStart); } set { if (Name != "") setComment(sectionStart, value); } } void setComment(IniFileElement el, string comment) { int index = parent.elements.IndexOf(el); if (IniFileSettings.CommentChars.Length == 0) throw new NotSupportedException("Comments are currently disabled. Setup ConfigFileSettings.CommentChars property to enable them."); IniFileCommentary com; if (index > 0 && parent.elements[index - 1] is IniFileCommentary) { com = ((IniFileCommentary)parent.elements[index - 1]); if (comment == "") parent.elements.Remove(com); else { com.Comment = comment; com.Intendation = el.Intendation; } } else if (comment != "") { com = IniFileCommentary.FromComment(comment); com.Intendation = el.Intendation; parent.elements.Insert(index, com); } } string getComment(IniFileElement el) { int index = parent.elements.IndexOf(el); if (index != 0 && parent.elements[index - 1] is IniFileCommentary) return ((IniFileCommentary)parent.elements[index - 1]).Comment; else return ""; } IniFileValue getValue(string key) { string lower = key.ToLowerInvariant(); IniFileValue val; for (int i = 0; i < elements.Count; i++) if (elements[i] is IniFileValue) { val = (IniFileValue)elements[i]; if (val.Key == key || (!IniFileSettings.CaseSensitive && val.Key.ToLowerInvariant() == lower)) return val; } return null; } /// <summary>Sets the comment for given key.</summary> public void SetComment(string key, string comment) { IniFileValue val = getValue(key); if (val == null) return; setComment(val, comment); } /// <summary>Sets the inline comment for given key.</summary> public void SetInlineComment(string key, string comment) { IniFileValue val = getValue(key); if (val == null) return; val.InlineComment = comment; } /// <summary>Gets the inline comment for given key.</summary> public string GetInlineComment(string key) { IniFileValue val = getValue(key); if (val == null) return null; return val.InlineComment; } /// <summary>Gets or sets the inline for this section.</summary> public string InlineComment { get { return sectionStart.InlineComment; } set { sectionStart.InlineComment = value; } } /// <summary>Gets the comment associated to given key. If there is no comment, empty string is returned. /// If the key does not exist, NULL is returned.</summary> public string GetComment(string key) { IniFileValue val = getValue(key); if (val == null) return null; return getComment(val); } /// <summary>Renames a key.</summary> public void RenameKey(string key, string newName) { IniFileValue v = getValue(key); if (key == null) return; v.Key = newName; } /// <summary>Deletes a key.</summary> public void DeleteKey(string key) { IniFileValue v = getValue(key); if (key == null) return; parent.elements.Remove(v); elements.Remove(v); } /// <summary>Gets or sets value of the key</summary> /// <param name="key">Name of key.</param> public string this[string key] { get { IniFileValue v = getValue(key); return v == null ? null : v.Value; } set { IniFileValue v; v = getValue(key); //if (!IniFileSettings.AllowEmptyValues && value == "") { // if (v != null) { // elements.Remove(v); // parent.elements.Remove(v); // return; // } //} if (v != null) { v.Value = value; return; } setValue(key, value); } } /// <summary>Gets or sets value of a key.</summary> /// <param name="key">Name of the key.</param> /// <param name="defaultValue">A value to return if the requested key was not found.</param> public string this[string key, string defaultValue] { get { string val = this[key]; if (val == "" || val == null) return defaultValue; return val; } set { this[key] = value; } } private void setValue(string key, string value) { IniFileValue ret = null; IniFileValue prev = lastValue(); if (IniFileSettings.PreserveFormatting) { if (prev != null && prev.Intendation.Length >= sectionStart.Intendation.Length) ret = prev.CreateNew(key, value); else { IniFileElement el; bool valFound = false; for (int i = parent.elements.IndexOf(sectionStart) - 1; i >= 0; i--) { el = parent.elements[i]; if (el is IniFileValue) { ret = ((IniFileValue)el).CreateNew(key, value); valFound = true; break; } } if (!valFound) ret = IniFileValue.FromData(key, value); if (ret.Intendation.Length < sectionStart.Intendation.Length) ret.Intendation = sectionStart.Intendation; } } else ret = IniFileValue.FromData(key, value); if (prev == null) { elements.Insert(elements.IndexOf(sectionStart) + 1, ret); parent.elements.Insert(parent.elements.IndexOf(sectionStart) + 1, ret); } else { elements.Insert(elements.IndexOf(prev) + 1, ret); parent.elements.Insert(parent.elements.IndexOf(prev) + 1, ret); } } internal IniFileValue lastValue() { for (int i = elements.Count - 1; i >= 0; i--) { if (elements[i] is IniFileValue) return (IniFileValue)elements[i]; } return null; } internal IniFileValue firstValue() { for (int i = 0; i < elements.Count; i++) { if (elements[i] is IniFileValue) return (IniFileValue)elements[i]; } return null; } /// <summary>Gets an array of names of values in this section.</summary> public System.Collections.ObjectModel.ReadOnlyCollection<string> GetKeys() { List<string> list = new List<string>(elements.Count); for (int i = 0; i < elements.Count; i++) if (elements[i] is IniFileValue) list.Add(((IniFileValue)elements[i]).Key); return new System.Collections.ObjectModel.ReadOnlyCollection<string>(list); ; } /// <summary>Gets a string representation of this IniFileSectionReader object.</summary> public override string ToString() { return sectionStart.ToString() + " (" + elements.Count.ToString() + " elements)"; } /// <summary>Formats whole section.</summary> /// <param name="preserveIntendation">Determines whether intendation should be preserved.</param> public void Format(bool preserveIntendation) { IniFileElement el; string lastIntend; for (int i = 0; i < elements.Count; i++) { el = elements[i]; lastIntend = el.Intendation; el.FormatDefault(); if (preserveIntendation) el.Intendation = lastIntend; } } } /// <summary>Static class containing format settings for INI files.</summary> public static class IniFileSettings { private static iniFlags flags = (iniFlags)255; private static string[] commentChars = { ";", "#" }; private static char? quoteChar = null; private static string defaultValueFormatting = "?=$ ;"; private static string defaultSectionFormatting = "[$] ;"; private static string sectionCloseBracket = "]"; private static string equalsString = "="; private static string tabReplacement = " "; private static string sectionOpenBracket = "["; private enum iniFlags { PreserveFormatting = 1, AllowEmptyValues = 2, AllowTextOnTheRight = 4, GroupElements = 8, CaseSensitive = 16, SeparateHeader = 32, AllowBlankLines = 64, AllowInlineComments = 128} //private static string DefaultCommentaryFormatting = ";$"; #region Public properties /// <summary>Inficates whether parser should preserve formatting. Default TRUE.</summary> public static bool PreserveFormatting { get { return (flags & iniFlags.PreserveFormatting) == iniFlags.PreserveFormatting; } set { if (value) flags = flags | iniFlags.PreserveFormatting; else flags = flags & ~iniFlags.PreserveFormatting; } } /// <summary>If true empty keys will not be removed. Default TRUE.</summary> public static bool AllowEmptyValues { get { return (flags & iniFlags.AllowEmptyValues) == iniFlags.AllowEmptyValues; } set { if (value) flags = flags | iniFlags.AllowEmptyValues; else flags = flags & ~iniFlags.AllowEmptyValues; } } /// <summary>If Quotes are on, then it in such situation: |KEY = "VALUE" blabla|, 'blabla' is /// a "text on the right". If this field is set to False, then such string will be ignored.</summary> public static bool AllowTextOnTheRight { get { return (flags & iniFlags.AllowTextOnTheRight) == iniFlags.AllowTextOnTheRight; } set { if (value) flags = flags | iniFlags.AllowTextOnTheRight; else flags = flags & ~iniFlags.AllowTextOnTheRight; } } /// <summary>Indicates whether comments and blank lines should be grouped /// (if true then multiple line comment will be parsed to the one single IniFileComment object). /// Otherwise, one IniFileElement will be always representing one single line in the file. Default TRUE.</summary> public static bool GroupElements { get { return (flags & iniFlags.GroupElements) == iniFlags.GroupElements; } set { if (value) flags = flags | iniFlags.GroupElements; else flags = flags & ~iniFlags.GroupElements; } } /// <summary>Determines whether all searching/testing operation are case-sensitive. Default TRUE.</summary> public static bool CaseSensitive { get { return (flags & iniFlags.CaseSensitive) == iniFlags.CaseSensitive; } set { if (value) flags = flags | iniFlags.CaseSensitive; else flags = flags & ~iniFlags.CaseSensitive; } } /// <summary>Determines whether a header comment of an INI file is separate from a comment of first section. /// If false, comment at the beginning of file may be considered both as header and commentary of the first section. Default TRUE.</summary> public static bool SeparateHeader { get { return (flags & iniFlags.SeparateHeader) == iniFlags.SeparateHeader; } set { if (value) flags = flags | iniFlags.SeparateHeader; else flags = flags & ~iniFlags.SeparateHeader; } } /// <summary>If true, blank lines will be written to a file. Otherwise, they will ignored.</summary> public static bool AllowBlankLines { get { return (flags & iniFlags.AllowBlankLines) == iniFlags.AllowBlankLines; } set { if (value) flags = flags | iniFlags.AllowBlankLines; else flags = flags & ~iniFlags.AllowBlankLines; } } /// <summary>If true, blank lines will be written to a file. Otherwise, they will ignored.</summary> public static bool AllowInlineComments { get { return (flags & iniFlags.AllowInlineComments) != 0; } set { if (value) flags |= iniFlags.AllowInlineComments; else flags &= ~iniFlags.AllowInlineComments; } } /// <summary>A string which represents close bracket for a section. If empty or null, sections will /// disabled. Default "]"</summary> public static string SectionCloseBracket { get { return IniFileSettings.sectionCloseBracket; } set { if (value == null) throw new ArgumentNullException("SectionCloseBracket"); IniFileSettings.sectionCloseBracket = value; } } /// <summary>Gets or sets array of strings which start a comment line. /// Default is {"#" (hash), ";" (semicolon)}. If empty or null, commentaries /// will not be allowed.</summary> public static string[] CommentChars { get { return IniFileSettings.commentChars; } set { if (value == null) throw new ArgumentNullException("CommentChars", "Use empty array to disable comments instead of null"); IniFileSettings.commentChars = value; } } /// <summary>Gets or sets a character which is used as quote. Default null (not using quotation marks).</summary> public static char? QuoteChar { get { return IniFileSettings.quoteChar; } set { IniFileSettings.quoteChar = value; } } /// <summary>A string which determines default formatting of section headers used in Format() method. /// '$' (dollar) means a section's name; '[' and ']' mean brackets; optionally, ';' is an inline comment. Default is "[$] ;" (e.g. "[Section] ;comment")</summary> public static string DefaultSectionFormatting { get { return IniFileSettings.defaultSectionFormatting; } set { if (value == null) throw new ArgumentNullException("DefaultSectionFormatting"); string test = value.Replace("$", "").Replace("[", "").Replace("]", "").Replace(";", ""); if (test.TrimStart().Length > 0) throw new ArgumentException("DefaultValueFormatting property cannot contain other characters than [,$,] and white spaces."); if (!(value.IndexOf('[') < value.IndexOf('$') && value.IndexOf('$') < value.IndexOf(']') && (value.IndexOf(';') == -1 || value.IndexOf(']') < value.IndexOf(';')))) throw new ArgumentException("Special charcters in the formatting strings are in the incorrect order. The valid is: [, $, ]."); IniFileSettings.defaultSectionFormatting = value; } } /// <summary>A string which determines default formatting of values used in Format() method. '?' (question mark) means a key, /// '$' (dollar) means a value and '=' (equality sign) means EqualsString; optionally, ';' is an inline comment. /// If QouteChar is not null, '$' will be automatically surrounded with qouetes. Default "?=$ ;" (e.g. "Key=Value ;comment".</summary> public static string DefaultValueFormatting { get { return IniFileSettings.defaultValueFormatting; } set { if (value == null) throw new ArgumentNullException("DefaultValueFormatting"); string test = value.Replace("?", "").Replace("$", "").Replace("=", "").Replace(";", ""); if (test.TrimStart().Length > 0) throw new ArgumentException("DefaultValueFormatting property cannot contain other characters than ?,$,= and white spaces."); if (!(((value.IndexOf('?') < value.IndexOf('=') && value.IndexOf('=') < value.IndexOf('$')) || (value.IndexOf('=') == -1 && test.IndexOf('?') < value.IndexOf('$'))) && (value.IndexOf(';') == -1 || value.IndexOf('$') < value.IndexOf(';')))) throw new ArgumentException("Special charcters in the formatting strings are in the incorrect order. The valid is: ?, =, $."); IniFileSettings.defaultValueFormatting = value; } } /// <summary>A string which represents open bracket for a section. If empty or null, sections will /// disabled. Default "[".</summary> public static string SectionOpenBracket { get { return IniFileSettings.sectionOpenBracket; } set { if (value == null) throw new ArgumentNullException("SectionCloseBracket"); IniFileSettings.sectionOpenBracket = value; } } /// <summary>Gets or sets string used as equality sign (which separates value from key). Default "=".</summary> public static string EqualsString { get { return IniFileSettings.equalsString; } set { if (value == null) throw new ArgumentNullException("EqualsString"); IniFileSettings.equalsString = value; } } /// <summary>The string which all tabs in intendentation will be replaced with. If null, tabs will not be replaced. Default " " (four spaces).</summary> public static string TabReplacement { get { return IniFileSettings.tabReplacement; } set { IniFileSettings.tabReplacement = value; } } #endregion internal static string trimLeft(ref string str) { int i = 0; StringBuilder ret = new StringBuilder(); while (i < str.Length && char.IsWhiteSpace(str, i)) { ret.Append(str[i]); i++; } if (str.Length > i) str = str.Substring(i); else str = ""; return ret.ToString(); } internal static string trimRight(ref string str) { int i = str.Length - 1; StringBuilder build = new StringBuilder(); while (i >= 0 && char.IsWhiteSpace(str, i)) { build.Append(str[i]); i--; } StringBuilder reversed = new StringBuilder(); for (int j = build.Length - 1; j >= 0; j--) reversed.Append(build[j]); if (str.Length - i > 0) str = str.Substring(0, i + 1); else str = ""; return reversed.ToString(); } internal static string startsWith(string line, string[] array) { if (array == null) return null; for (int i = 0; i < array.Length; i++) if (line.StartsWith(array[i])) return array[i]; return null; } internal struct indexOfAnyResult { public int index; public string any; public indexOfAnyResult(int i, string _any) { any = _any; index = i; } } internal static indexOfAnyResult indexOfAny(string text, string[] array) { for (int i = 0; i < array.Length; i++) if (text.Contains(array[i])) return new indexOfAnyResult(text.IndexOf(array[i]), array[i]); return new indexOfAnyResult(-1, null); } internal static string ofAny(int index, string text, string[] array) { for (int i = 0; i < array.Length; i++) if (text.Length - index >= array[i].Length && text.Substring(index, array[i].Length) == array[i]) return array[i]; return null; } //internal static string endsWith(string line, string[] array) //{ // if (array == null) return null; // for (int i = 0; i < array.Length; i++) // if (line.EndsWith(array[i])) // return array[i]; // return null; //} } }
/* * 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 apigateway-2015-07-09.normal.json service model. */ using System; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.APIGateway; using Amazon.APIGateway.Model; using Amazon.APIGateway.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using Amazon.Util; using ServiceClientGenerator; using AWSSDK_DotNet35.UnitTests.TestTools; namespace AWSSDK_DotNet35.UnitTests.Marshalling { [TestClass] public partial class APIGatewayMarshallingTests { static readonly ServiceModel service_model = Utils.LoadServiceModel("apigateway-2015-07-09.normal.json", "apigateway.customizations.json"); [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void CreateApiKeyMarshallTest() { var operation = service_model.FindOperation("CreateApiKey"); var request = InstantiateClassGenerator.Execute<CreateApiKeyRequest>(); var marshaller = new CreateApiKeyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("CreateApiKey", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = CreateApiKeyResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as CreateApiKeyResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void CreateBasePathMappingMarshallTest() { var operation = service_model.FindOperation("CreateBasePathMapping"); var request = InstantiateClassGenerator.Execute<CreateBasePathMappingRequest>(); var marshaller = new CreateBasePathMappingRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("CreateBasePathMapping", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = CreateBasePathMappingResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as CreateBasePathMappingResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void CreateDeploymentMarshallTest() { var operation = service_model.FindOperation("CreateDeployment"); var request = InstantiateClassGenerator.Execute<CreateDeploymentRequest>(); var marshaller = new CreateDeploymentRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("CreateDeployment", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = CreateDeploymentResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as CreateDeploymentResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void CreateDomainNameMarshallTest() { var operation = service_model.FindOperation("CreateDomainName"); var request = InstantiateClassGenerator.Execute<CreateDomainNameRequest>(); var marshaller = new CreateDomainNameRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("CreateDomainName", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = CreateDomainNameResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as CreateDomainNameResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void CreateModelMarshallTest() { var operation = service_model.FindOperation("CreateModel"); var request = InstantiateClassGenerator.Execute<CreateModelRequest>(); var marshaller = new CreateModelRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("CreateModel", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = CreateModelResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as CreateModelResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void CreateResourceMarshallTest() { var operation = service_model.FindOperation("CreateResource"); var request = InstantiateClassGenerator.Execute<CreateResourceRequest>(); var marshaller = new CreateResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("CreateResource", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = CreateResourceResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as CreateResourceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void CreateRestApiMarshallTest() { var operation = service_model.FindOperation("CreateRestApi"); var request = InstantiateClassGenerator.Execute<CreateRestApiRequest>(); var marshaller = new CreateRestApiRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("CreateRestApi", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = CreateRestApiResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as CreateRestApiResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void CreateStageMarshallTest() { var operation = service_model.FindOperation("CreateStage"); var request = InstantiateClassGenerator.Execute<CreateStageRequest>(); var marshaller = new CreateStageRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("CreateStage", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = CreateStageResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as CreateStageResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void DeleteApiKeyMarshallTest() { var operation = service_model.FindOperation("DeleteApiKey"); var request = InstantiateClassGenerator.Execute<DeleteApiKeyRequest>(); var marshaller = new DeleteApiKeyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteApiKey", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void DeleteBasePathMappingMarshallTest() { var operation = service_model.FindOperation("DeleteBasePathMapping"); var request = InstantiateClassGenerator.Execute<DeleteBasePathMappingRequest>(); var marshaller = new DeleteBasePathMappingRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteBasePathMapping", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void DeleteClientCertificateMarshallTest() { var operation = service_model.FindOperation("DeleteClientCertificate"); var request = InstantiateClassGenerator.Execute<DeleteClientCertificateRequest>(); var marshaller = new DeleteClientCertificateRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteClientCertificate", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void DeleteDeploymentMarshallTest() { var operation = service_model.FindOperation("DeleteDeployment"); var request = InstantiateClassGenerator.Execute<DeleteDeploymentRequest>(); var marshaller = new DeleteDeploymentRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteDeployment", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void DeleteDomainNameMarshallTest() { var operation = service_model.FindOperation("DeleteDomainName"); var request = InstantiateClassGenerator.Execute<DeleteDomainNameRequest>(); var marshaller = new DeleteDomainNameRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteDomainName", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void DeleteIntegrationMarshallTest() { var operation = service_model.FindOperation("DeleteIntegration"); var request = InstantiateClassGenerator.Execute<DeleteIntegrationRequest>(); var marshaller = new DeleteIntegrationRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteIntegration", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void DeleteIntegrationResponseMarshallTest() { var operation = service_model.FindOperation("DeleteIntegrationResponse"); var request = InstantiateClassGenerator.Execute<DeleteIntegrationResponseRequest>(); var marshaller = new DeleteIntegrationResponseRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteIntegrationResponse", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void DeleteMethodMarshallTest() { var operation = service_model.FindOperation("DeleteMethod"); var request = InstantiateClassGenerator.Execute<DeleteMethodRequest>(); var marshaller = new DeleteMethodRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteMethod", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void DeleteMethodResponseMarshallTest() { var operation = service_model.FindOperation("DeleteMethodResponse"); var request = InstantiateClassGenerator.Execute<DeleteMethodResponseRequest>(); var marshaller = new DeleteMethodResponseRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteMethodResponse", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void DeleteModelMarshallTest() { var operation = service_model.FindOperation("DeleteModel"); var request = InstantiateClassGenerator.Execute<DeleteModelRequest>(); var marshaller = new DeleteModelRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteModel", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void DeleteResourceMarshallTest() { var operation = service_model.FindOperation("DeleteResource"); var request = InstantiateClassGenerator.Execute<DeleteResourceRequest>(); var marshaller = new DeleteResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteResource", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void DeleteRestApiMarshallTest() { var operation = service_model.FindOperation("DeleteRestApi"); var request = InstantiateClassGenerator.Execute<DeleteRestApiRequest>(); var marshaller = new DeleteRestApiRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteRestApi", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void DeleteStageMarshallTest() { var operation = service_model.FindOperation("DeleteStage"); var request = InstantiateClassGenerator.Execute<DeleteStageRequest>(); var marshaller = new DeleteStageRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteStage", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void FlushStageCacheMarshallTest() { var operation = service_model.FindOperation("FlushStageCache"); var request = InstantiateClassGenerator.Execute<FlushStageCacheRequest>(); var marshaller = new FlushStageCacheRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("FlushStageCache", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GenerateClientCertificateMarshallTest() { var operation = service_model.FindOperation("GenerateClientCertificate"); var request = InstantiateClassGenerator.Execute<GenerateClientCertificateRequest>(); var marshaller = new GenerateClientCertificateRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GenerateClientCertificate", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GenerateClientCertificateResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GenerateClientCertificateResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetAccountMarshallTest() { var operation = service_model.FindOperation("GetAccount"); var request = InstantiateClassGenerator.Execute<GetAccountRequest>(); var marshaller = new GetAccountRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetAccount", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetAccountResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetAccountResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetApiKeyMarshallTest() { var operation = service_model.FindOperation("GetApiKey"); var request = InstantiateClassGenerator.Execute<GetApiKeyRequest>(); var marshaller = new GetApiKeyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetApiKey", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetApiKeyResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetApiKeyResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetApiKeysMarshallTest() { var operation = service_model.FindOperation("GetApiKeys"); var request = InstantiateClassGenerator.Execute<GetApiKeysRequest>(); var marshaller = new GetApiKeysRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetApiKeys", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetApiKeysResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetApiKeysResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetBasePathMappingMarshallTest() { var operation = service_model.FindOperation("GetBasePathMapping"); var request = InstantiateClassGenerator.Execute<GetBasePathMappingRequest>(); var marshaller = new GetBasePathMappingRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetBasePathMapping", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetBasePathMappingResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetBasePathMappingResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetBasePathMappingsMarshallTest() { var operation = service_model.FindOperation("GetBasePathMappings"); var request = InstantiateClassGenerator.Execute<GetBasePathMappingsRequest>(); var marshaller = new GetBasePathMappingsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetBasePathMappings", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetBasePathMappingsResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetBasePathMappingsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetClientCertificateMarshallTest() { var operation = service_model.FindOperation("GetClientCertificate"); var request = InstantiateClassGenerator.Execute<GetClientCertificateRequest>(); var marshaller = new GetClientCertificateRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetClientCertificate", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetClientCertificateResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetClientCertificateResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetClientCertificatesMarshallTest() { var operation = service_model.FindOperation("GetClientCertificates"); var request = InstantiateClassGenerator.Execute<GetClientCertificatesRequest>(); var marshaller = new GetClientCertificatesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetClientCertificates", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetClientCertificatesResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetClientCertificatesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetDeploymentMarshallTest() { var operation = service_model.FindOperation("GetDeployment"); var request = InstantiateClassGenerator.Execute<GetDeploymentRequest>(); var marshaller = new GetDeploymentRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetDeployment", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetDeploymentResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetDeploymentResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetDeploymentsMarshallTest() { var operation = service_model.FindOperation("GetDeployments"); var request = InstantiateClassGenerator.Execute<GetDeploymentsRequest>(); var marshaller = new GetDeploymentsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetDeployments", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetDeploymentsResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetDeploymentsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetDomainNameMarshallTest() { var operation = service_model.FindOperation("GetDomainName"); var request = InstantiateClassGenerator.Execute<GetDomainNameRequest>(); var marshaller = new GetDomainNameRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetDomainName", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetDomainNameResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetDomainNameResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetDomainNamesMarshallTest() { var operation = service_model.FindOperation("GetDomainNames"); var request = InstantiateClassGenerator.Execute<GetDomainNamesRequest>(); var marshaller = new GetDomainNamesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetDomainNames", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetDomainNamesResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetDomainNamesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetIntegrationMarshallTest() { var operation = service_model.FindOperation("GetIntegration"); var request = InstantiateClassGenerator.Execute<GetIntegrationRequest>(); var marshaller = new GetIntegrationRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetIntegration", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetIntegrationResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetIntegrationResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetIntegrationResponseMarshallTest() { var operation = service_model.FindOperation("GetIntegrationResponse"); var request = InstantiateClassGenerator.Execute<GetIntegrationResponseRequest>(); var marshaller = new GetIntegrationResponseRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetIntegrationResponse", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetIntegrationResponseResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetIntegrationResponseResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetMethodMarshallTest() { var operation = service_model.FindOperation("GetMethod"); var request = InstantiateClassGenerator.Execute<GetMethodRequest>(); var marshaller = new GetMethodRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetMethod", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetMethodResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetMethodResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetMethodResponseMarshallTest() { var operation = service_model.FindOperation("GetMethodResponse"); var request = InstantiateClassGenerator.Execute<GetMethodResponseRequest>(); var marshaller = new GetMethodResponseRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetMethodResponse", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetMethodResponseResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetMethodResponseResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetModelMarshallTest() { var operation = service_model.FindOperation("GetModel"); var request = InstantiateClassGenerator.Execute<GetModelRequest>(); var marshaller = new GetModelRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetModel", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetModelResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetModelResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetModelsMarshallTest() { var operation = service_model.FindOperation("GetModels"); var request = InstantiateClassGenerator.Execute<GetModelsRequest>(); var marshaller = new GetModelsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetModels", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetModelsResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetModelsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetModelTemplateMarshallTest() { var operation = service_model.FindOperation("GetModelTemplate"); var request = InstantiateClassGenerator.Execute<GetModelTemplateRequest>(); var marshaller = new GetModelTemplateRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetModelTemplate", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetModelTemplateResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetModelTemplateResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetResourceMarshallTest() { var operation = service_model.FindOperation("GetResource"); var request = InstantiateClassGenerator.Execute<GetResourceRequest>(); var marshaller = new GetResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetResource", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetResourceResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetResourceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetResourcesMarshallTest() { var operation = service_model.FindOperation("GetResources"); var request = InstantiateClassGenerator.Execute<GetResourcesRequest>(); var marshaller = new GetResourcesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetResources", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetResourcesResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetResourcesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetRestApiMarshallTest() { var operation = service_model.FindOperation("GetRestApi"); var request = InstantiateClassGenerator.Execute<GetRestApiRequest>(); var marshaller = new GetRestApiRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetRestApi", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetRestApiResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetRestApiResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetRestApisMarshallTest() { var operation = service_model.FindOperation("GetRestApis"); var request = InstantiateClassGenerator.Execute<GetRestApisRequest>(); var marshaller = new GetRestApisRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetRestApis", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetRestApisResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetRestApisResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetSdkMarshallTest() { var operation = service_model.FindOperation("GetSdk"); var request = InstantiateClassGenerator.Execute<GetSdkRequest>(); var marshaller = new GetSdkRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetSdk", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"Content-Disposition","Content-Disposition_Value"}, {"Content-Type","Content-Type_Value"}, {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetSdkResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetSdkResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetStageMarshallTest() { var operation = service_model.FindOperation("GetStage"); var request = InstantiateClassGenerator.Execute<GetStageRequest>(); var marshaller = new GetStageRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetStage", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetStageResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetStageResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void GetStagesMarshallTest() { var operation = service_model.FindOperation("GetStages"); var request = InstantiateClassGenerator.Execute<GetStagesRequest>(); var marshaller = new GetStagesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetStages", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetStagesResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetStagesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void PutIntegrationMarshallTest() { var operation = service_model.FindOperation("PutIntegration"); var request = InstantiateClassGenerator.Execute<PutIntegrationRequest>(); var marshaller = new PutIntegrationRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("PutIntegration", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = PutIntegrationResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as PutIntegrationResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void PutIntegrationResponseMarshallTest() { var operation = service_model.FindOperation("PutIntegrationResponse"); var request = InstantiateClassGenerator.Execute<PutIntegrationResponseRequest>(); var marshaller = new PutIntegrationResponseRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("PutIntegrationResponse", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = PutIntegrationResponseResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as PutIntegrationResponseResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void PutMethodMarshallTest() { var operation = service_model.FindOperation("PutMethod"); var request = InstantiateClassGenerator.Execute<PutMethodRequest>(); var marshaller = new PutMethodRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("PutMethod", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = PutMethodResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as PutMethodResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void PutMethodResponseMarshallTest() { var operation = service_model.FindOperation("PutMethodResponse"); var request = InstantiateClassGenerator.Execute<PutMethodResponseRequest>(); var marshaller = new PutMethodResponseRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("PutMethodResponse", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = PutMethodResponseResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as PutMethodResponseResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void TestInvokeMethodMarshallTest() { var operation = service_model.FindOperation("TestInvokeMethod"); var request = InstantiateClassGenerator.Execute<TestInvokeMethodRequest>(); var marshaller = new TestInvokeMethodRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("TestInvokeMethod", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = TestInvokeMethodResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as TestInvokeMethodResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateAccountMarshallTest() { var operation = service_model.FindOperation("UpdateAccount"); var request = InstantiateClassGenerator.Execute<UpdateAccountRequest>(); var marshaller = new UpdateAccountRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateAccount", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateAccountResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateAccountResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateApiKeyMarshallTest() { var operation = service_model.FindOperation("UpdateApiKey"); var request = InstantiateClassGenerator.Execute<UpdateApiKeyRequest>(); var marshaller = new UpdateApiKeyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateApiKey", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateApiKeyResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateApiKeyResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateBasePathMappingMarshallTest() { var operation = service_model.FindOperation("UpdateBasePathMapping"); var request = InstantiateClassGenerator.Execute<UpdateBasePathMappingRequest>(); var marshaller = new UpdateBasePathMappingRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateBasePathMapping", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateBasePathMappingResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateBasePathMappingResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateClientCertificateMarshallTest() { var operation = service_model.FindOperation("UpdateClientCertificate"); var request = InstantiateClassGenerator.Execute<UpdateClientCertificateRequest>(); var marshaller = new UpdateClientCertificateRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateClientCertificate", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateClientCertificateResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateClientCertificateResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateDeploymentMarshallTest() { var operation = service_model.FindOperation("UpdateDeployment"); var request = InstantiateClassGenerator.Execute<UpdateDeploymentRequest>(); var marshaller = new UpdateDeploymentRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateDeployment", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateDeploymentResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateDeploymentResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateDomainNameMarshallTest() { var operation = service_model.FindOperation("UpdateDomainName"); var request = InstantiateClassGenerator.Execute<UpdateDomainNameRequest>(); var marshaller = new UpdateDomainNameRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateDomainName", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateDomainNameResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateDomainNameResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateIntegrationMarshallTest() { var operation = service_model.FindOperation("UpdateIntegration"); var request = InstantiateClassGenerator.Execute<UpdateIntegrationRequest>(); var marshaller = new UpdateIntegrationRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateIntegration", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateIntegrationResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateIntegrationResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateIntegrationResponseMarshallTest() { var operation = service_model.FindOperation("UpdateIntegrationResponse"); var request = InstantiateClassGenerator.Execute<UpdateIntegrationResponseRequest>(); var marshaller = new UpdateIntegrationResponseRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateIntegrationResponse", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateIntegrationResponseResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateIntegrationResponseResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateMethodMarshallTest() { var operation = service_model.FindOperation("UpdateMethod"); var request = InstantiateClassGenerator.Execute<UpdateMethodRequest>(); var marshaller = new UpdateMethodRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateMethod", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateMethodResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateMethodResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateMethodResponseMarshallTest() { var operation = service_model.FindOperation("UpdateMethodResponse"); var request = InstantiateClassGenerator.Execute<UpdateMethodResponseRequest>(); var marshaller = new UpdateMethodResponseRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateMethodResponse", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateMethodResponseResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateMethodResponseResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateModelMarshallTest() { var operation = service_model.FindOperation("UpdateModel"); var request = InstantiateClassGenerator.Execute<UpdateModelRequest>(); var marshaller = new UpdateModelRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateModel", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateModelResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateModelResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateResourceMarshallTest() { var operation = service_model.FindOperation("UpdateResource"); var request = InstantiateClassGenerator.Execute<UpdateResourceRequest>(); var marshaller = new UpdateResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateResource", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateResourceResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateResourceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateRestApiMarshallTest() { var operation = service_model.FindOperation("UpdateRestApi"); var request = InstantiateClassGenerator.Execute<UpdateRestApiRequest>(); var marshaller = new UpdateRestApiRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateRestApi", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateRestApiResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateRestApiResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("APIGateway")] public void UpdateStageMarshallTest() { var operation = service_model.FindOperation("UpdateStage"); var request = InstantiateClassGenerator.Execute<UpdateStageRequest>(); var marshaller = new UpdateStageRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateStage", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateStageResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateStageResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Axiom.Core; using System.IO; using System.Diagnostics; using Axiom.Graphics; using Axiom.MathLib; using Axiom.Configuration; using Axiom.Collections; using Axiom.Animating; using Axiom.ParticleSystems; using Axiom.Serialization; using Multiverse.ToolBox; namespace Multiverse.Tools.WorldEditor { public partial class AddPlantTypeDialog : Form { private Color ColorExToColor(ColorEx cx) { return Color.FromArgb((int)cx.ToARGB()); } private ColorEx ColorToColorEx(Color c) { return new ColorEx(c.A / 255f, c.R / 255f, c.G / 255f, c.B / 255f); } public AddPlantTypeDialog(string title, List<AssetDesc> list, WorldEditor app) { InitializeComponent(); ColorEx color = new ColorEx(); color = app.Config.PlantColorDefault; colorDialog1.Color = ColorExToColor(color); colorSelectButton.BackColor = colorDialog1.Color; int colorabgr = (int)color.ToABGR(); int[] colorsabgr = new int[1]; colorabgr &= 0x00ffffff; colorsabgr[0] = colorabgr; colorDialog1.CustomColors = colorsabgr; foreach (AssetDesc asset in list) { imageNameComboBox.Items.Add(asset.Name); } imageNameComboBox.SelectedIndex = 0; } private void colorSelectButton_Click(object sender, EventArgs e) { colorDialog1.ShowDialog(); colorSelectButton.BackColor = colorDialog1.Color; } public string ComboBoxSelected { get { return imageNameComboBox.SelectedItem.ToString(); } } public ColorEx ColorRGB { get { return ColorToColorEx(colorDialog1.Color); } set { colorDialog1.Color = ColorExToColor(value); } } public string MinimumWidthScaleTextBoxText { get { return minimumWidthScaleTextBox.Text; } set { minimumWidthScaleTextBox.Text = value; } } public string MaximumWidthScaleTextBoxText { get { return maximumWidthScaleTextBox.Text; } set { maximumWidthScaleTextBox.Text = value; } } public string MinimumHeightScaleTextBoxText { get { return minimumHeightScaleTextBox.Text; } set { minimumHeightScaleTextBox.Text = value; } } public string MaximumHeightScaleTextBoxText { get { return maximumHeightScaleTextBox.Text; } set { maximumHeightScaleTextBox.Text = value; } } public string ColorMultLowTextBoxText { get { return colorMultLowTextBox.Text; } set { colorMultLowTextBox.Text = value; } } public string ColorMultHiTextBoxText { get { return colorMultHiTextBox.Text; } set { colorMultHiTextBox.Text = value; } } public string InstancesTextBoxText { get { return instancesTextBox.Text; } set { instancesTextBox.Text = value; } } public string WindMagnitudeTextBoxText { get { return windMagnitudeTextBox.Text; } set { windMagnitudeTextBox.Text = value; } } public float MinimumWidthScale { get { return float.Parse(minimumWidthScaleTextBox.Text); } set { minimumWidthScaleTextBox.Text = value.ToString(); } } public float MaximumWidthScale { get { return float.Parse(maximumWidthScaleTextBox.Text); } set { maximumWidthScaleTextBox.Text = value.ToString(); } } public float MinimumHeightScale { get { return float.Parse(minimumHeightScaleTextBox.Text); } set { minimumHeightScaleTextBox.Text = value.ToString(); } } public float MaximumHeightScale { get { return float.Parse(maximumHeightScaleTextBox.Text); } set { maximumHeightScaleTextBox.Text = value.ToString(); } } public float ColorMultLow { get { return float.Parse(colorMultLowTextBox.Text); } set { colorMultLowTextBox.Text = value.ToString(); } } public float ColorMultHi { get { return float.Parse(colorMultHiTextBox.Text); } set { colorMultHiTextBox.Text = value.ToString(); } } public uint Instances { get { return uint.Parse(instancesTextBox.Text); } set { instancesTextBox.Text = value.ToString(); } } public float WindMagnitude { get { return float.Parse(windMagnitudeTextBox.Text); } set { windMagnitudeTextBox.Text = value.ToString(); } } private void floatVerifyevent(object sender, CancelEventArgs e) { TextBox textbox = (TextBox)sender; if (!ValidityHelperClass.isFloat(textbox.Text)) { Color textColor = Color.Red; textbox.ForeColor = textColor; } else { Color textColor = Color.Black; textbox.ForeColor = textColor; } } private void uIntVerifyevent(object sender, CancelEventArgs e) { TextBox textbox = (TextBox)sender; if (!ValidityHelperClass.isUint(textbox.Text)) { Color textColor = Color.Red; textbox.ForeColor = textColor; } else { Color textColor = Color.Black; textbox.ForeColor = textColor; } } public bool okButton_validating() { if (!ValidityHelperClass.isFloat(minimumWidthScaleTextBox.Text)) { MessageBox.Show("Minimum width scale can not be parsed to a floating point number", "Incorrect minimum width scale", MessageBoxButtons.OK); return false; } else { if (!ValidityHelperClass.isFloat(maximumWidthScaleTextBox.Text)) { MessageBox.Show("Maximum width scale can not be parsed to a floating point number", "Maximum width scale", MessageBoxButtons.OK); return false; } else { if (!ValidityHelperClass.isFloat(minimumHeightScaleTextBox.Text)) { MessageBox.Show("Minimum height scale can not be parsed to a floating point number", "Incorrect minimum height scale", MessageBoxButtons.OK); return false; } else { if (!ValidityHelperClass.isFloat(maximumHeightScaleTextBox.Text)) { MessageBox.Show("Maximum height scale can not be parsed to a floating point number", "Incorrect maximum height scale", MessageBoxButtons.OK); return false; } else { if (!ValidityHelperClass.isFloat(colorMultLowTextBox.Text)) { MessageBox.Show("Color muliplier low can not be parsed to a floating point number", "Incorrect color multiplier low", MessageBoxButtons.OK); return false; } else { if (!ValidityHelperClass.isFloat(colorMultHiTextBox.Text)) { MessageBox.Show("Color multiplier high can not be parsed to a floating point number", "Incorrect color multiplier high", MessageBoxButtons.OK); return false; } else { if (!ValidityHelperClass.isUint(instancesTextBox.Text)) { MessageBox.Show("Instances can not be parsed to a unsigned integer number", "Incorrect instances", MessageBoxButtons.OK); return false; } else { if (!ValidityHelperClass.isFloat(windMagnitudeTextBox.Text)) { MessageBox.Show("Wind magnitude can not be parsed to a floating point number", "Incorrect wind magnitude", MessageBoxButtons.OK); return false; } } } } } } } } return true; } private void helpButton_clicked(object sender, EventArgs e) { Button but = sender as Button; WorldEditor.LaunchDoc(but.Tag as string); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed partial class ExpressionBinder { // ---------------------------------------------------------------------------- // BindImplicitConversion // ---------------------------------------------------------------------------- private sealed class ImplicitConversion { public ImplicitConversion(ExpressionBinder binder, Expr exprSrc, CType typeSrc, ExprClass typeDest, bool needsExprDest, CONVERTTYPE flags) { _binder = binder; _exprSrc = exprSrc; _typeSrc = typeSrc; _typeDest = typeDest.Type; _exprTypeDest = typeDest; _needsExprDest = needsExprDest; _flags = flags; _exprDest = null; } public Expr ExprDest { get { return _exprDest; } } private Expr _exprDest; private readonly ExpressionBinder _binder; private readonly Expr _exprSrc; private readonly CType _typeSrc; private readonly CType _typeDest; private readonly ExprClass _exprTypeDest; private readonly bool _needsExprDest; private CONVERTTYPE _flags; /* * BindImplicitConversion * * This is a complex routine with complex parameters. Generally, this should * be called through one of the helper methods that insulates you * from the complexity of the interface. This routine handles all the logic * associated with implicit conversions. * * exprSrc - the expression being converted. Can be null if only type conversion * info is being supplied. * typeSrc - type of the source * typeDest - type of the destination * exprDest - returns an expression of the src converted to the dest. If null, we * only care about whether the conversion can be attempted, not the * expression tree. * flags - flags possibly customizing the conversions allowed. E.g., can suppress * user-defined conversions. * * returns true if the conversion can be made, false if not. */ public bool Bind() { // 13.1 Implicit conversions // // The following conversions are classified as implicit conversions: // // * Identity conversions // * Implicit numeric conversions // * Implicit enumeration conversions // * Implicit reference conversions // * Boxing conversions // * Implicit type parameter conversions // * Implicit constant expression conversions // * User-defined implicit conversions // * Implicit conversions from an anonymous method expression to a compatible delegate type // * Implicit conversion from a method group to a compatible delegate type // * Conversions from the null type (11.2.7) to any nullable type // * Implicit nullable conversions // * Lifted user-defined implicit conversions // // Implicit conversions can occur in a variety of situations, including function member invocations // (14.4.3), cast expressions (14.6.6), and assignments (14.14). // Can't convert to or from the error type. if (_typeSrc == null || _typeDest == null || _typeDest.IsNeverSameType()) { return false; } Debug.Assert(_typeSrc != null && _typeDest != null); // types must be supplied. Debug.Assert(_exprSrc == null || _typeSrc == _exprSrc.Type); // type of source should be correct if source supplied Debug.Assert(!_needsExprDest || _exprSrc != null); // need source expr to create dest expr switch (_typeDest.GetTypeKind()) { case TypeKind.TK_ErrorType: Debug.Assert(_typeDest.AsErrorType().HasTypeParent() || _typeDest.AsErrorType().HasNSParent()); if (_typeSrc != _typeDest) { return false; } if (_needsExprDest) { _exprDest = _exprSrc; } return true; case TypeKind.TK_NullType: // Can only convert to the null type if src is null. if (!_typeSrc.IsNullType()) { return false; } if (_needsExprDest) { _exprDest = _exprSrc; } return true; case TypeKind.TK_MethodGroupType: VSFAIL("Something is wrong with Type.IsNeverSameType()"); return false; case TypeKind.TK_NaturalIntegerType: case TypeKind.TK_ArgumentListType: return _typeSrc == _typeDest; case TypeKind.TK_VoidType: return false; default: break; } if (_typeSrc.IsErrorType()) { Debug.Assert(!_typeDest.IsErrorType()); return false; } // 13.1.1 Identity conversion // // An identity conversion converts from any type to the same type. This conversion exists only // such that an entity that already has a required type can be said to be convertible to that type. if (_typeSrc == _typeDest && ((_flags & CONVERTTYPE.ISEXPLICIT) == 0 || (!_typeSrc.isPredefType(PredefinedType.PT_FLOAT) && !_typeSrc.isPredefType(PredefinedType.PT_DOUBLE)))) { if (_needsExprDest) { _exprDest = _exprSrc; } return true; } if (_typeDest.IsNullableType()) { return BindNubConversion(_typeDest.AsNullableType()); } if (_typeSrc.IsNullableType()) { return bindImplicitConversionFromNullable(_typeSrc.AsNullableType()); } if ((_flags & CONVERTTYPE.ISEXPLICIT) != 0) { _flags |= CONVERTTYPE.NOUDC; } // Get the fundamental types of destination. FUNDTYPE ftDest = _typeDest.fundType(); Debug.Assert(ftDest != FUNDTYPE.FT_NONE || _typeDest.IsParameterModifierType()); switch (_typeSrc.GetTypeKind()) { default: VSFAIL("Bad type symbol kind"); break; case TypeKind.TK_MethodGroupType: if (_exprSrc is ExprMemberGroup memGrp) { ExprCall outExpr; bool retVal = _binder.BindGrpConversion(memGrp, _typeDest, _needsExprDest, out outExpr, false); _exprDest = outExpr; return retVal; } return false; case TypeKind.TK_VoidType: case TypeKind.TK_ErrorType: case TypeKind.TK_ParameterModifierType: case TypeKind.TK_ArgumentListType: return false; case TypeKind.TK_NullType: if (bindImplicitConversionFromNull()) { return true; } // If not, try user defined implicit conversions. break; case TypeKind.TK_ArrayType: if (bindImplicitConversionFromArray()) { return true; } // If not, try user defined implicit conversions. break; case TypeKind.TK_PointerType: if (bindImplicitConversionFromPointer()) { return true; } // If not, try user defined implicit conversions. break; case TypeKind.TK_TypeParameterType: if (bindImplicitConversionFromTypeVar(_typeSrc.AsTypeParameterType())) { return true; } // If not, try user defined implicit conversions. break; case TypeKind.TK_AggregateType: // TypeReference and ArgIterator can't be boxed (or converted to anything else) if (_typeSrc.isSpecialByRefType()) { return false; } if (bindImplicitConversionFromAgg(_typeSrc.AsAggregateType())) { return true; } // If not, try user defined implicit conversions. break; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // // Every incoming dynamic operand should be implicitly convertible // to any type that it is an instance of. object srcRuntimeObject = _exprSrc?.RuntimeObject; if (srcRuntimeObject != null && _typeDest.AssociatedSystemType.IsInstanceOfType(srcRuntimeObject) && _binder.GetSemanticChecker().CheckTypeAccess(_typeDest, _binder.Context.ContextForMemberLookup)) { if (_needsExprDest) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, _exprSrc.Flags & EXPRFLAG.EXF_CANTBENULL); } return true; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // END RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // 13.1.8 User-defined implicit conversions // // A user-defined implicit conversion consists of an optional standard implicit conversion, // followed by execution of a user-defined implicit conversion operator, followed by another // optional standard implicit conversion. The exact rules for evaluating user-defined // conversions are described in 13.4.3. if (0 == (_flags & CONVERTTYPE.NOUDC)) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, true); } // No conversion was found. return false; } /*************************************************************************************************** Called by BindImplicitConversion when the destination type is Nullable<T>. The following conversions are handled by this method: * For S in { object, ValueType, interfaces implemented by underlying type} there is an explicit unboxing conversion S => T? * System.Enum => T? there is an unboxing conversion if T is an enum type * null => T? implemented as default(T?) * Implicit T?* => T?+ implemented by either wrapping or calling GetValueOrDefault the appropriate number of times. * If imp/exp S => T then imp/exp S => T?+ implemented by converting to T then wrapping the appropriate number of times. * If imp/exp S => T then imp/exp S?+ => T?+ implemented by calling GetValueOrDefault (m-1) times then calling HasValue, producing a null if it returns false, otherwise calling Value, converting to T then wrapping the appropriate number of times. The 3 rules above can be summarized with the following recursive rules: * If imp/exp S => T? then imp/exp S? => T? implemented as qs.HasValue ? (T?)(qs.Value) : default(T?) * If imp/exp S => T then imp/exp S => T? implemented as new T?((T)s) This method also handles calling bindUserDefinedConverion. This method does NOT handle the following conversions: * Implicit boxing conversion from S? to { object, ValueType, Enum, ifaces implemented by S }. (Handled by BindImplicitConversion.) * If imp/exp S => T then explicit S?+ => T implemented by calling Value the appropriate number of times. (Handled by BindExplicitConversion.) The recursive equivalent is: * If imp/exp S => T and T is not nullable then explicit S? => T implemented as qs.Value Some nullable conversion are NOT standard conversions. In particular, if S => T is implicit then S? => T is not standard. Similarly if S => T is not implicit then S => T? is not standard. ***************************************************************************************************/ private bool BindNubConversion(NullableType nubDst) { // This code assumes that STANDARD and ISEXPLICIT are never both set. // bindUserDefinedConversion should ensure this! Debug.Assert(0 != (~_flags & (CONVERTTYPE.STANDARD | CONVERTTYPE.ISEXPLICIT))); Debug.Assert(_exprSrc == null || _exprSrc.Type == _typeSrc); Debug.Assert(!_needsExprDest || _exprSrc != null); Debug.Assert(_typeSrc != nubDst); // BindImplicitConversion should have taken care of this already. AggregateType atsDst = nubDst.GetAts(GetErrorContext()); if (atsDst == null) return false; // Check for the unboxing conversion. This takes precedence over the wrapping conversions. if (GetSymbolLoader().HasBaseConversion(nubDst.GetUnderlyingType(), _typeSrc) && !CConversions.FWrappingConv(_typeSrc, nubDst)) { // These should be different! Fix the caller if typeSrc is an AggregateType of Nullable. Debug.Assert(atsDst != _typeSrc); // typeSrc is a base type of the destination nullable type so there is an explicit // unboxing conversion. if (0 == (_flags & CONVERTTYPE.ISEXPLICIT)) { return false; } if (_needsExprDest) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); } return true; } int cnubDst; int cnubSrc; CType typeDstBase = nubDst.StripNubs(out cnubDst); ExprClass exprTypeDstBase = GetExprFactory().MakeClass(typeDstBase); CType typeSrcBase = _typeSrc.StripNubs(out cnubSrc); ConversionFunc pfn = (_flags & CONVERTTYPE.ISEXPLICIT) != 0 ? (ConversionFunc)_binder.BindExplicitConversion : (ConversionFunc)_binder.BindImplicitConversion; if (cnubSrc == 0) { Debug.Assert(_typeSrc == typeSrcBase); // The null type can be implicitly converted to T? as the default value. if (_typeSrc.IsNullType()) { // If we have the constant null, generate it as a default value of T?. If we have // some crazy expression which has been determined to be always null, like (null??null) // keep it in its expression form and transform it in the nullable rewrite pass. if (_needsExprDest) { if (_exprSrc.isCONSTANT_OK()) { _exprDest = GetExprFactory().CreateZeroInit(nubDst); } else { _exprDest = GetExprFactory().CreateCast(0x00, _typeDest, _exprSrc); } } return true; } Expr exprTmp = _exprSrc; // If there is an implicit/explicit S => T then there is an implicit/explicit S => T? if (_typeSrc == typeDstBase || pfn(_exprSrc, _typeSrc, exprTypeDstBase, nubDst, _needsExprDest, out exprTmp, _flags | CONVERTTYPE.NOUDC)) { if (_needsExprDest) { ExprUserDefinedConversion exprUDC = exprTmp as ExprUserDefinedConversion; if (exprUDC != null) { exprTmp = exprUDC.UserDefinedCall; } // This logic is left over from the days when T?? was legal. However there are error/LAF cases that necessitates the loop. // typeSrc is not nullable so just wrap the required number of times. For legal code (cnubDst <= 0). for (int i = 0; i < cnubDst; i++) { ExprCall call = _binder.BindNubNew(exprTmp); exprTmp = call; call.NullableCallLiftKind = NullableCallLiftKind.NullableConversionConstructor; } if (exprUDC != null) { exprUDC.UserDefinedCall = exprTmp; exprTmp = exprUDC; } Debug.Assert(exprTmp.Type == nubDst); _exprDest = exprTmp; } return true; } // No builtin conversion. Maybe there is a user defined conversion.... return 0 == (_flags & CONVERTTYPE.NOUDC) && _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, nubDst, _needsExprDest, out _exprDest, 0 == (_flags & CONVERTTYPE.ISEXPLICIT)); } // Both are Nullable so there is only a conversion if there is a conversion between the base types. // That is, if there is an implicit/explicit S => T then there is an implicit/explicit S?+ => T?+. if (typeSrcBase != typeDstBase && !pfn(null, typeSrcBase, exprTypeDstBase, nubDst, false, out _exprDest, _flags | CONVERTTYPE.NOUDC)) { // No builtin conversion. Maybe there is a user defined conversion.... return 0 == (_flags & CONVERTTYPE.NOUDC) && _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, nubDst, _needsExprDest, out _exprDest, 0 == (_flags & CONVERTTYPE.ISEXPLICIT)); } if (_needsExprDest) { MethWithInst mwi = new MethWithInst(null, null); ExprMemberGroup pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); ExprCall exprDst = GetExprFactory().CreateCall(0, nubDst, _exprSrc, pMemGroup, null); // Here we want to first check whether or not the conversions work on the base types. Expr arg1 = _binder.mustCast(_exprSrc, typeSrcBase); ExprClass arg2 = GetExprFactory().MakeClass(typeDstBase); bool convertible; if (0 != (_flags & CONVERTTYPE.ISEXPLICIT)) { convertible = _binder.BindExplicitConversion(arg1, arg1.Type, arg2, typeDstBase, out arg1, _flags | CONVERTTYPE.NOUDC); } else { convertible = _binder.BindImplicitConversion(arg1, arg1.Type, arg2, typeDstBase, out arg1, _flags | CONVERTTYPE.NOUDC); } if (!convertible) { VSFAIL("bind(Im|Ex)plicitConversion failed unexpectedly"); return false; } exprDst.CastOfNonLiftedResultToLiftedType = _binder.mustCast(arg1, nubDst, 0); exprDst.NullableCallLiftKind = NullableCallLiftKind.NullableConversion; exprDst.PConversions = exprDst.CastOfNonLiftedResultToLiftedType; _exprDest = exprDst; } return true; } private bool bindImplicitConversionFromNull() { // null type can be implicitly converted to any reference type or pointer type or type // variable with reference-type constraint. FUNDTYPE ftDest = _typeDest.fundType(); if (ftDest != FUNDTYPE.FT_REF && ftDest != FUNDTYPE.FT_PTR && (ftDest != FUNDTYPE.FT_VAR || !_typeDest.AsTypeParameterType().IsReferenceType()) && // null is convertible to System.Nullable<T>. !_typeDest.isPredefType(PredefinedType.PT_G_OPTIONAL)) { return false; } if (_needsExprDest) { // If the conversion argument is a constant null then return a ZEROINIT. // Otherwise, bind this as a cast to the destination type. In a later // rewrite pass we will rewrite the cast as SEQ(side effects, ZEROINIT). if (_exprSrc.isCONSTANT_OK()) { _exprDest = GetExprFactory().CreateZeroInit(_typeDest); } else { _exprDest = GetExprFactory().CreateCast(0x00, _typeDest, _exprSrc); } } return true; } private bool bindImplicitConversionFromNullable(NullableType nubSrc) { // We can convert T? using a boxing conversion, we can convert it to ValueType, and // we can convert it to any interface implemented by T. // // 13.1.5 Boxing Conversions // // A nullable-type has a boxing conversion to the same set of types to which the nullable-type's // underlying type has boxing conversions. A boxing conversion applied to a value of a nullable-type // proceeds as follows: // // * If the HasValue property of the nullable value evaluates to false, then the result of the // boxing conversion is the null reference of the appropriate type. // // Otherwise, the result is obtained by boxing the result of evaluating the Value property on // the nullable value. AggregateType atsNub = nubSrc.GetAts(GetErrorContext()); if (atsNub == null) { return false; } if (atsNub == _typeDest) { if (_needsExprDest) { _exprDest = _exprSrc; } return true; } if (GetSymbolLoader().HasBaseConversion(nubSrc.GetUnderlyingType(), _typeDest) && !CConversions.FUnwrappingConv(nubSrc, _typeDest)) { if (_needsExprDest) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_BOX); if (!_typeDest.isPredefType(PredefinedType.PT_OBJECT)) { // The base type of a nullable is always a non-nullable value type, // therefore so is typeDest unless typeDest is PT_OBJECT. In this case the conversion // needs to be unboxed. We only need this if we actually will use the result. _binder.bindSimpleCast(_exprDest, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_UNBOX); } } return true; } return 0 == (_flags & CONVERTTYPE.NOUDC) && _binder.bindUserDefinedConversion(_exprSrc, nubSrc, _typeDest, _needsExprDest, out _exprDest, true); } private bool bindImplicitConversionFromArray() { // 13.1.4 // // The implicit reference conversions are: // // * From an array-type S with an element type SE to an array-type T with an element // type TE, provided all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * An implicit reference conversion exists from SE to TE. // * From a one-dimensional array-type S[] to System.Collections.Generic.IList<S>, // System.Collections.Generic.IReadOnlyList<S> and their base interfaces // * From a one-dimensional array-type S[] to System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> // and their base interfaces, provided there is an implicit reference conversion from S to T. // * From any array-type to System.Array. // * From any array-type to any interface implemented by System.Array. if (!GetSymbolLoader().HasBaseConversion(_typeSrc, _typeDest)) { return false; } EXPRFLAG grfex = 0; // The above if checks for dest==Array, object or an interface the array implements, // including IList<T>, ICollection<T>, IEnumerable<T>, IReadOnlyList<T>, IReadOnlyCollection<T> // and the non-generic versions. if ((_typeDest.IsArrayType() || (_typeDest.isInterfaceType() && _typeDest.AsAggregateType().GetTypeArgsAll().Count == 1 && ((_typeDest.AsAggregateType().GetTypeArgsAll()[0] != _typeSrc.AsArrayType().GetElementType()) || 0 != (_flags & CONVERTTYPE.FORCECAST)))) && (0 != (_flags & CONVERTTYPE.FORCECAST) || TypeManager.TypeContainsTyVars(_typeSrc, null) || TypeManager.TypeContainsTyVars(_typeDest, null))) { grfex = EXPRFLAG.EXF_REFCHECK; } if (_needsExprDest) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, grfex); } return true; } private bool bindImplicitConversionFromPointer() { // 27.4 Pointer conversions // // In an unsafe context, the set of available implicit conversions (13.1) is extended to include // the following implicit pointer conversions: // // * From any pointer-type to the type void*. if (_typeDest.IsPointerType() && _typeDest.AsPointerType().GetReferentType() == _binder.getVoidType()) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return true; } return false; } private bool bindImplicitConversionFromAgg(AggregateType aggTypeSrc) { // GENERICS: The case for constructed types is very similar to types with // no parameters. The parameters are irrelevant for most of the conversions // below. They could be relevant if we had user-defined conversions on // generic types. AggregateSymbol aggSrc = aggTypeSrc.getAggregate(); if (aggSrc.IsEnum()) { return bindImplicitConversionFromEnum(aggTypeSrc); } if (_typeDest.isEnumType()) { if (bindImplicitConversionToEnum(aggTypeSrc)) { return true; } // Even though enum is sealed, a class can derive from enum in LAF scenarios -- // continue testing for derived to base conversions below. } else if (aggSrc.getThisType().isSimpleType() && _typeDest.isSimpleType()) { if (bindImplicitConversionBetweenSimpleTypes(aggTypeSrc)) { return true; } // No simple conversion -- continue testing for derived to base conversions below. } return bindImplicitConversionToBase(aggTypeSrc); } private bool bindImplicitConversionToBase(AggregateType pSource) { // 13.1.4 Implicit reference conversions // // * From any reference-type to object. // * From any class-type S to any class-type T, provided S is derived from T. // * From any class-type S to any interface-type T, provided S implements T. // * From any interface-type S to any interface-type T, provided S is derived from T. // * From any delegate-type to System.Delegate. // * From any delegate-type to System.ICloneable. if (!_typeDest.IsAggregateType() || !GetSymbolLoader().HasBaseConversion(pSource, _typeDest)) { return false; } EXPRFLAG flags = 0x00; if (pSource.getAggregate().IsStruct() && _typeDest.fundType() == FUNDTYPE.FT_REF) { flags = EXPRFLAG.EXF_BOX | EXPRFLAG.EXF_CANTBENULL; } else if (_exprSrc != null) { flags = _exprSrc.Flags & EXPRFLAG.EXF_CANTBENULL; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, flags); return true; } private bool bindImplicitConversionFromEnum(AggregateType aggTypeSrc) { // 13.1.5 Boxing conversions // // A boxing conversion permits any non-nullable-value-type to be implicitly converted to the type // object or System.ValueType or to any interface-type implemented by the value-type, and any enum // type to be implicitly converted to System.Enum as well. Boxing a value of a // non-nullable-value-type consists of allocating an object instance and copying the value-type // value into that instance. An enum can be boxed to the type System.Enum, since that is the direct // base class for all enums (21.4). A struct or enum can be boxed to the type System.ValueType, // since that is the direct base class for all structs (18.3.2) and a base class for all enums. if (_typeDest.IsAggregateType() && GetSymbolLoader().HasBaseConversion(aggTypeSrc, _typeDest.AsAggregateType())) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_BOX | EXPRFLAG.EXF_CANTBENULL); return true; } return false; } private bool bindImplicitConversionToEnum(AggregateType aggTypeSrc) { // The spec states: // ***************** // 13.1.3 Implicit enumeration conversions // // An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any // enum-type. // ***************** // However, we actually allow any constant zero, not just the integer literal zero, to be converted // to enum. The reason for this is for backwards compatibility with a premature optimization // that used to be in the binding layer. We would optimize away expressions such as 0 | blah to be // just 0, but not erase the "is literal" bit. This meant that expression such as 0 | 0 | E.X // would succeed rather than correctly producing an error pointing out that 0 | 0 is not a literal // zero and therefore does not convert to any enum. // // We have removed the premature optimization but want old code to continue to compile. Rather than // try to emulate the somewhat complex behaviour of the previous optimizer, it is easier to simply // say that any compile time constant zero is convertible to any enum. This means unfortunately // expressions such as (7-7) * 12 are convertible to enum, but frankly, that's better than having // some terribly complex rule about what constitutes a legal zero and what doesn't. // Note: Don't use GetConst here since the conversion only applies to bona-fide compile time constants. if ( aggTypeSrc.getAggregate().GetPredefType() != PredefinedType.PT_BOOL && _exprSrc != null && _exprSrc.IsZero() && _exprSrc.Type.isNumericType() && /*(exprSrc.flags & EXF_LITERALCONST) &&*/ 0 == (_flags & CONVERTTYPE.STANDARD)) { // NOTE: This allows conversions from uint, long, ulong, float, double, and hexadecimal int // NOTE: This is for backwards compatibility with Everett // This is another place where we lose Expr fidelity. We shouldn't fold this // into a constant here - we should move this to a later pass. if (_needsExprDest) { _exprDest = GetExprFactory().CreateConstant(_typeDest, ConstVal.GetDefaultValue(_typeDest.constValKind())); } return true; } return false; } private bool bindImplicitConversionBetweenSimpleTypes(AggregateType aggTypeSrc) { AggregateSymbol aggSrc = aggTypeSrc.getAggregate(); Debug.Assert(aggSrc.getThisType().isSimpleType()); Debug.Assert(_typeDest.isSimpleType()); Debug.Assert(aggSrc.IsPredefined() && _typeDest.isPredefined()); PredefinedType ptSrc = aggSrc.GetPredefType(); PredefinedType ptDest = _typeDest.getPredefType(); ConvKind convertKind; bool fConstShrinkCast = false; Debug.Assert((int)ptSrc < NUM_SIMPLE_TYPES && (int)ptDest < NUM_SIMPLE_TYPES); // 13.1.7 Implicit constant expression conversions // // An implicit constant expression conversion permits the following conversions: // * A constant-expression (14.16) of type int can be converted to type sbyte, byte, short, // ushort, uint, or ulong, provided the value of the constant-expression is within the range // of the destination type. // * A constant-expression of type long can be converted to type ulong, provided the value of // the constant-expression is not negative. // Note: Don't use GetConst here since the conversion only applies to bona-fide compile time constants. if (_exprSrc is ExprConstant constant && _exprSrc.IsOK && ((ptSrc == PredefinedType.PT_INT && ptDest != PredefinedType.PT_BOOL && ptDest != PredefinedType.PT_CHAR) || (ptSrc == PredefinedType.PT_LONG && ptDest == PredefinedType.PT_ULONG)) && isConstantInRange(constant, _typeDest)) { // Special case (CLR 6.1.6): if integral constant is in range, the conversion is a legal implicit conversion. convertKind = ConvKind.Implicit; fConstShrinkCast = _needsExprDest && (GetConvKind(ptSrc, ptDest) != ConvKind.Implicit); } else if (ptSrc == ptDest) { // Special case: precision limiting casts to float or double Debug.Assert(ptSrc == PredefinedType.PT_FLOAT || ptSrc == PredefinedType.PT_DOUBLE); Debug.Assert(0 != (_flags & CONVERTTYPE.ISEXPLICIT)); convertKind = ConvKind.Implicit; } else { convertKind = GetConvKind(ptSrc, ptDest); Debug.Assert(convertKind != ConvKind.Identity); // identity conversion should have been handled at first. } if (convertKind != ConvKind.Implicit) { return false; } // An implicit conversion exists. Do the conversion. if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, false); if (result == ConstCastResult.Success) { return true; // else, don't fold and use a regular cast, below. } } if (isUserDefinedConversion(ptSrc, ptDest)) { if (!_needsExprDest) { return true; } // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the NOUDC flag here. return _binder.bindUserDefinedConversion(_exprSrc, aggTypeSrc, _typeDest, _needsExprDest, out _exprDest, true); } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return true; } private bool bindImplicitConversionFromTypeVar(TypeParameterType tyVarSrc) { // 13.1.4 // // For a type-parameter T that is known to be a reference type (25.7), the following implicit // reference conversions exist: // // * From T to its effective base class C, from T to any base class of C, and from T to any // interface implemented by C. // * From T to an interface-type I in T's effective interface set and from T to any base // interface of I. // * From T to a type parameter U provided that T depends on U (25.7). [Note: Since T is known // to be a reference type, within the scope of T, the run-time type of U will always be a // reference type, even if U is not known to be a reference type at compile-time.] // * From the null type (11.2.7) to T. // // 13.1.5 // // For a type-parameter T that is not known to be a reference type (25.7), the following conversions // involving T are considered to be boxing conversions at compile-time. At run-time, if T is a value // type, the conversion is executed as a boxing conversion. At run-time, if T is a reference type, // the conversion is executed as an implicit reference conversion or identity conversion. // // * From T to its effective base class C, from T to any base class of C, and from T to any // interface implemented by C. [Note: C will be one of the types System.Object, System.ValueType, // or System.Enum (otherwise T would be known to be a reference type and 13.1.4 would apply // instead of this clause).] // * From T to an interface-type I in T's effective interface set and from T to any base // interface of I. // // 13.1.6 Implicit type parameter conversions // // This clause details implicit conversions involving type parameters that are not classified as // implicit reference conversions or implicit boxing conversions. // // For a type-parameter T that is not known to be a reference type, there is an implicit conversion // from T to a type parameter U provided T depends on U. At run-time, if T is a value type and U is // a reference type, the conversion is executed as a boxing conversion. At run-time, if both T and U // are value types, then T and U are necessarily the same type and no conversion is performed. At // run-time, if T is a reference type, then U is necessarily also a reference type and the conversion // is executed as an implicit reference conversion or identity conversion (25.7). CType typeTmp = tyVarSrc.GetEffectiveBaseClass(); TypeArray bnds = tyVarSrc.GetBounds(); int itype = -1; for (; ;) { if (_binder.canConvert(typeTmp, _typeDest, _flags | CONVERTTYPE.NOUDC)) { if (!_needsExprDest) { return true; } if (_typeDest.IsTypeParameterType()) { // For a type var destination we need to cast to object then to the other type var. Expr exprT; ExprClass exprObj = GetExprFactory().MakeClass(_binder.GetReqPDT(PredefinedType.PT_OBJECT)); _binder.bindSimpleCast(_exprSrc, exprObj, out exprT, EXPRFLAG.EXF_FORCE_BOX); _binder.bindSimpleCast(exprT, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_UNBOX); } else { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_BOX); } return true; } do { if (++itype >= bnds.Count) { return false; } typeTmp = bnds[itype]; } while (!typeTmp.isInterfaceType() && !typeTmp.IsTypeParameterType()); } } private SymbolLoader GetSymbolLoader() { return _binder.GetSymbolLoader(); } private ExprFactory GetExprFactory() { return _binder.GetExprFactory(); } private ErrorHandling GetErrorContext() { return _binder.GetErrorContext(); } } } }
using System; namespace UnityEngine.Experimental { public struct VectorArray<T> { public const uint k_InvalidIdx = uint.MaxValue; private T[] m_array; // backing storage private uint m_offset; // offset into backing storage private uint m_count; // active slots, <= m_array.Length private bool m_clearToDefault; // if true, freed up slots will be default initialized public VectorArray(uint capacity, bool clearToDefault) { m_array = new T[capacity]; m_offset = 0; m_count = capacity; m_clearToDefault = clearToDefault; } public VectorArray(T[] array, uint offset, uint count, bool clearToDefault) { m_array = array; m_offset = offset; m_count = count; m_clearToDefault = clearToDefault; } public VectorArray(ref VectorArray<T> vec, uint offset, uint count) { m_array = vec.m_array; m_offset = vec.m_offset + offset; m_count = count; m_clearToDefault = vec.m_clearToDefault; } // Reset fill count, but keep storage public void Reset() { if (m_clearToDefault) { for (uint i = 0; i < m_count; ++i) this[i] = default(T); } m_count = 0; } // Reset fill count and reserve enough storage public void Reset(uint capacity) { if (m_array.Length < (m_offset + capacity)) { m_array = new T[capacity]; m_offset = 0; m_count = 0; } else Reset(); } // Reserve additional storage public void Reserve(uint capacity) { if (m_offset + m_count + capacity <= m_array.Length) return; if (m_count == 0) { m_array = new T[capacity]; } else { T[] tmp = new T[m_count + capacity]; Array.Copy(m_array, m_offset, tmp, 0, m_count); m_array = tmp; } m_offset = 0; } // Resize array, either by cutting off at the end, or adding potentially default initialized slots // Resize will modify the count member as well, whereas reserve won't. public void Resize(uint size) { if (size > m_count) { uint residue = size - m_count; Reserve(residue); } else if (m_clearToDefault) { for (uint i = size; i < m_count; ++i) this[i] = default(T); } m_count = size; } public delegate void Cleanup(T obj); // Same as Resize(), with an additional delegate to do any cleanup on the potentially freed slots public void Resize(uint size, Cleanup cleanupDelegate) { for (uint i = size; i < m_count; ++i) cleanupDelegate(this[i]); Resize(size); } // Same as Reset(), with an additional delegate to do any cleanup on the potentially freed slots public void Reset(Cleanup cleanupDelegate) { for (uint i = 0; i < m_count; ++i) cleanupDelegate(this[i]); Reset(); } // Same as Reset( uint capacity ), with an additional delegate to do any cleanup on the potentially freed slots public void Reset(uint capacity, Cleanup cleanupDelegate) { for (uint i = 0; i < m_count; ++i) cleanupDelegate(this[i]); Reset(capacity); } // Add obj and reallocate if necessary. Returns the index where the object was added. public uint Add(T obj) { Reserve(1); uint idx = m_count; this[idx] = obj; m_count++; return idx; } // Add multiple objects and reallocate if necessary. Returns the index where the first object was added. public uint Add(T[] objs, uint count) { Reserve(count); return AddUnchecked(objs, count); } public uint Add(ref VectorArray<T> vec) { Reserve(vec.Count()); return AddUnchecked(ref vec); } // Add an object without doing size checks. Make sure to call Reserve( capacity ) before using this. public uint AddUnchecked(T obj) { uint idx = m_count; this[idx] = obj; m_count++; return idx; } // Add multiple objects without doing size checks. Make sure to call Reserve( capacity ) before using this. public uint AddUnchecked(T[] objs, uint count) { uint idx = m_count; Array.Copy(objs, 0, m_array, m_offset + idx, count); m_count += count; return idx; } public uint AddUnchecked(ref VectorArray<T> vec) { uint cnt = vec.Count(); uint idx = m_count; Array.Copy(vec.m_array, vec.m_offset, m_array, m_offset + idx, cnt); m_count += cnt; return idx; } // Purge count number of elements from the end of the array. public void Purge(uint count) { Resize(count > m_count ? 0 : (m_count - count)); } // Same as Purge with an additional cleanup delegate. public void Purge(uint count, Cleanup cleanupDelegate) { Resize(count > m_count ? 0 : (m_count - count), cleanupDelegate); } // Copies the active elements to the destination. destination.Length must be large enough to hold all values. public void CopyTo(T[] destination, int destinationStart, out uint count) { count = m_count; Array.Copy(m_array, m_offset, destination, destinationStart, count); } // Swaps two elements in the array doing bounds checks. public void Swap(uint first, uint second) { if (first >= m_count || second >= m_count) throw new System.ArgumentException("Swap indices are out of range."); SwapUnchecked(first, second); } // Swaps two elements without any checks. public void SwapUnchecked(uint first, uint second) { T tmp = this[first]; this[first] = this[second]; this[second] = tmp; } // Extracts information from objects contained in the array and stores them in the destination array. // Conversion is performed by the extractor delegate for each object. // The destination array must be large enough to hold all values. // The output parameter count will contain the number of actual objects written out to the destination array. public delegate U Extractor<U>(T obj); public void ExtractTo<U>(U[] destination, int destinationStart, out uint count, Extractor<U> extractorDelegate) { if (destination.Length < m_count) throw new System.ArgumentException("Destination array is too small for source array."); count = m_count; for (uint i = 0; i < m_count; ++i) destination[destinationStart + i] = extractorDelegate(this[i]); } public void ExtractTo<U>(ref VectorArray<U> destination, Extractor<U> extractorDelegate) { destination.Reserve(m_count); for (uint i = 0; i < m_count; ++i) destination.AddUnchecked(extractorDelegate(this[i])); } // Cast to array. The output parameter will contain the array offset to valid members and the number of active elements. // Accessing array elements outside of this interval will lead to undefined behavior. public T[] AsArray(out uint offset, out uint count) { offset = m_offset; count = m_count; return m_array; } // Array access. No bounds checking here, make sure you know what you're doing. public T this[uint index] { get { return m_array[m_offset + index]; } set { m_array[m_offset + index] = value; } } // Returns the number of active elements in the vector. public uint Count() { return m_count; } // Returns the total capacity of accessible backing storage public uint CapacityTotal() { return (uint)m_array.Length - m_offset; } // Return the number of slots that can still be added before reallocation of the backing storage becomes necessary. public uint CapacityAvailable() { return (uint)m_array.Length - m_offset - m_count; } // Default sort the active array content. public void Sort() { Debug.Assert(m_count <= int.MaxValue && m_offset <= int.MaxValue); Array.Sort(m_array, (int)m_offset, (int)m_count); } // Returns true if the element matches the designator according to the comparator. idx will hold the index to the first matched object in the array. public delegate bool Comparator<U>(ref U designator, ref T obj); public bool FindFirst<U>(out uint idx, ref U designator, Comparator<U> compareDelegate) { for (idx = 0; idx < m_count; ++idx) { T obj = this[idx]; if (compareDelegate(ref designator, ref obj)) return true; } idx = k_InvalidIdx; return false; } // Returns true if the element matches the designator using the types native compare method. idx will hold the index to the first matched object in the array. public bool FindFirst(out uint idx, ref T designator) { for (idx = 0; idx < m_count; ++idx) { if (this[idx].Equals(designator)) return true; } idx = k_InvalidIdx; return false; } // Returns a vector representing a subrange. Contents are shared, not duplicated. public VectorArray<T> Subrange(uint offset, uint count) { return new VectorArray<T>(m_array, m_offset + offset, count, m_clearToDefault); } } }
//! \file ArcPulltop.cs //! \date Sun Nov 29 04:43:52 2015 //! \brief Pulltop archives implementation. // // Copyright (C) 2015 by morkt // // 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 GameRes.Utility; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Text; using GameRes.Formats.Strings; using GameRes.Compression; namespace GameRes.Formats.Will { [Export(typeof(ArchiveFormat))] public class Arc2Opener : ArchiveFormat { public override string Tag { get { return "ARC/WillV2"; } } public override string Description { get { return "Will Co. game engine resource archive v2"; } } public override uint Signature { get { return 0; } } public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return true; } } public Arc2Opener () { Extensions = new string[] { "arc", "ar2" }; ContainedFormats = new[] { "PNG", "PNA", "PSB", "OGG", "SCR" }; } public override ArcFile TryOpen (ArcView file) { int count = file.View.ReadInt32 (0); if (!IsSaneCount (count)) return null; uint index_offset = 8; uint index_size = file.View.ReadUInt32 (4); uint base_offset = index_offset + index_size; if (index_size > base_offset || base_offset >= file.MaxOffset) return null; file.View.Reserve (index_offset, index_size); var dir = new List<Entry> (count); var name_buffer = new StringBuilder (0x40); for (int i = 0; i < count; ++i) { if (index_offset >= base_offset) return null; uint size = file.View.ReadUInt32 (index_offset); long offset = (long)base_offset + file.View.ReadUInt32 (index_offset+4); index_offset += 8; name_buffer.Clear(); for (;;) { if (index_offset >= base_offset) return null; char c = (char)file.View.ReadUInt16 (index_offset); index_offset += 2; if (0 == c) break; name_buffer.Append (c); } if (0 == name_buffer.Length) return null; var name = name_buffer.ToString(); var entry = Create<Entry> (name); entry.Offset = offset; entry.Size = size; if (!entry.CheckPlacement (file.MaxOffset)) return null; dir.Add (entry); } if (index_offset != base_offset) return null; return new ArcFile (file, this, dir); } public override Stream OpenEntry (ArcFile arc, Entry entry) { if (!IsScriptFile (entry.Name) || Path.GetFileName (arc.File.Name).Contains ("Model")) { if (entry.Name.HasExtension (".PSP")) return OpenPsp (arc, entry); return base.OpenEntry (arc, entry); } var data = arc.File.View.ReadBytes (entry.Offset, entry.Size); for (int i = 0; i < data.Length; ++i) { data[i] = Binary.RotByteR (data[i], 2); } return new BinMemoryStream (data, entry.Name); } Stream OpenPsp (ArcFile arc, Entry entry) { using (var input = arc.File.CreateStream (entry.Offset, entry.Size)) { int unpacked_size = input.ReadInt32(); var output = new byte[unpacked_size]; int dst = 0; var frame = new byte[0x1000]; int frame_pos = 1; while (dst < unpacked_size) { int ctl = input.ReadByte(); for (int bit = 1; dst < unpacked_size && bit != 0x100; bit <<= 1) { if (0 != (ctl & bit)) { byte b = input.ReadUInt8(); output[dst++] = frame[frame_pos++ & 0xFFF] = b; } else { int hi = input.ReadByte(); int lo = input.ReadByte(); int offset = hi << 4 | lo >> 4; for (int count = 2 + (lo & 0xF); count != 0; --count) { byte v = frame[offset++ & 0xFFF]; output[dst++] = frame[frame_pos++ & 0xFFF] = v; } } } } return new BinMemoryStream (output, entry.Name); } } static bool IsScriptFile (string name) { return name.HasAnyOfExtensions ("ws2", "json"); } public override void Create (Stream output, IEnumerable<Entry> list, ResourceOptions options, EntryCallback callback) { int file_count = list.Count(); var names = new List<byte[]> (file_count); int index_size = 0; foreach (var entry in list) { var utf16_name = Encoding.Unicode.GetBytes (Path.GetFileName (entry.Name)); names.Add (utf16_name); index_size += 8 + utf16_name.Length + 2; } int callback_count = 0; uint current_offset = 0; output.Position = 8 + index_size; foreach (var entry in list) { if (null != callback) callback (callback_count++, entry, arcStrings.MsgAddingFile); entry.Offset = current_offset; using (var input = File.OpenRead (entry.Name)) { var size = input.Length; if (size > uint.MaxValue || current_offset + size > uint.MaxValue) throw new FileSizeException(); if (IsScriptFile (entry.Name)) CopyScript (input, output); else input.CopyTo (output); current_offset += (uint)size; entry.Size = (uint)size; } } if (null != callback) callback (callback_count++, null, arcStrings.MsgWritingIndex); output.Position = 0; using (var writer = new BinaryWriter (output, Encoding.Unicode, true)) { writer.Write (file_count); writer.Write (index_size); int i = 0; foreach (var entry in list) { writer.Write (entry.Size); writer.Write ((uint)entry.Offset); writer.Write (names[i++]); writer.Write ((short)0); } } } void CopyScript (Stream input, Stream output) { var buffer = new byte[81920]; for (;;) { int read = input.Read (buffer, 0, buffer.Length); if (0 == read) break; for (int i = 0; i < read; ++i) { buffer[i] = Binary.RotByteL (buffer[i], 2); } output.Write (buffer, 0, read); } } } [Export(typeof(ResourceAlias))] [ExportMetadata("Extension", "PSP")] [ExportMetadata("Target", "PSB")] public class PspFormat : ResourceAlias { } }
using UnityEngine; using System.Collections; using SmoothMoves; /// <summary> /// This class controls the enemies of the game /// </summary> public class ROTD_Pasta : MonoBehaviour { /// <summary> /// Internal reference to the game manager /// </summary> private ROTD_GameManager _gameManager; /// <summary> /// Internal cache of the transform /// </summary> private Transform _thisTransform; /// <summary> /// Internal timer countdown until the pasta checks on the chef's position /// </summary> private float _checkDirectionTimeLeft; /// <summary> /// Internal cache of the offset of the pasta from the chef /// </summary> private Vector3 _offset; /// <summary> /// Direction to move /// </summary> private Vector3 _moveDirection; /// <summary> /// Internal cache of the pasta's position /// </summary> private Vector3 _position; /// <summary> /// Internal cache of the pasta's rotation /// </summary> private Vector3 _localEulerAngles; /// <summary> /// Pasta's state /// </summary> private STATE _state; /// <summary> /// Direction from which the pasta was hit /// </summary> private float _hitXDirection; /// <summary> /// Internal countdown timer of when the pasta can move again /// </summary> private float _waitingToMoveTimeLeft; /// <summary> /// The amount of health left in the pasta /// </summary> private float _healthLeft; /// <summary> /// Internal reference to the live animation of the pasta /// </summary> private BoneAnimation _liveAnimation; /// <summary> /// Internal reference to the trail left by the pasta /// </summary> private Transform _trailTransform; /// <summary> /// Possible states of the pasta /// </summary> public enum STATE { Initializing, Spawning, WaitingToMove, Moving, Hitting, Attacking, Dying, Dead } /// <summary> /// Possible types of pasta /// </summary> public enum TYPE { Pizza } /// <summary> /// The type of this pasta /// </summary> public TYPE pastaType; /// <summary> /// Reference to the prefab of the live animation /// </summary> public GameObject liveAnimationPrefab; /// <summary> /// Reference to the particle system that leaves a trail /// </summary> public ParticleSystem trailParticles; /// <summary> /// Z position of the trail so that it is always behind foreground objects /// </summary> public float trailZPosition; /// <summary> /// Reference to the gameobject that contains colliders /// </summary> public GameObject colliderGameObject; /// <summary> /// Sound of the pasta getting hit /// </summary> public AudioSource hitSound; /// <summary> /// Sound of the pasta dying /// </summary> public AudioSource splatSound; /// <summary> /// Sound of the pasta attacking the chef /// </summary> public AudioSource attackSound; /// <summary> /// Initial health of the pasta /// </summary> public float health; /// <summary> /// Amount of damage the pasta can do /// </summary> public float damage; /// <summary> /// The speed the pasta travels at /// </summary> public float moveSpeed; /// <summary> /// The minimum attack range in the x and y axis /// </summary> public Vector2 minAttackRange; /// <summary> /// The minimum and maximum pitch for the attack sound (for variety) /// </summary> public Vector2 minMaxAttackSoundPitch; /// <summary> /// The amount of time before the pasta can move after stopping or getting hit /// </summary> public float waitToMoveTime; /// <summary> /// The minimum and maximum check direction times /// A random value will be picked between the x and y values /// Stored as a vector2 instead of two separate variables for simplicity /// </summary> public Vector2 minMaxCheckDirectionTime; /// <summary> /// The speed the pasta flies at when hit /// </summary> public float hitMoveSpeed; /// <summary> /// State of the pasta /// </summary> public STATE State { get { return _state; } set { // only uodate the state if it has changed if (_state != value) { _state = value; switch (_state) { case STATE.Spawning: // the pasta is coming alive, // turn off the trail particles and play the Spawn animation trailParticles.enableEmission = false; _liveAnimation.Play("Spawn"); break; case STATE.WaitingToMove: // the pasta is waiting to move, // turn off the trail particles, set the wait to move countdown, and play the Stand animation trailParticles.enableEmission = false; #if UNITY_3_5 colliderGameObject.active = true; #else colliderGameObject.SetActive(true); #endif _waitingToMoveTimeLeft = waitToMoveTime; _liveAnimation.CrossFade("Stand"); break; case STATE.Moving: // the pasta is moving, // turn on the trail particles and play the Move animation trailParticles.enableEmission = true; _liveAnimation.CrossFade("Move"); break; case STATE.Hitting: // the pasta is being hit, // turn off the trail particles and play the Hit animation trailParticles.enableEmission = false; _liveAnimation.Play("Hit"); break; case STATE.Attacking: // the pasta is attacking, // turn off the trail particles and play the Attack animation trailParticles.enableEmission = false; _liveAnimation.Play("Attack"); break; case STATE.Dying: // the pasta is dying, // play the splat sound, activate the splat animation, // stop the live animation, deactivate the animation gameobject, // turn off the trail particles, and turn off the collider splatSound.Play(); _gameManager.fxManager.Activate(ROTD_FX.FX_TYPE.Pizza_Splat, _thisTransform.position, (int)UnityEngine.Random.Range(-1.0f, 1.0f), ""); _liveAnimation.Stop(); #if UNITY_3_5 _liveAnimation.gameObject.SetActiveRecursively(false); #else _liveAnimation.gameObject.SetActive(false); #endif trailParticles.enableEmission = false; #if UNITY_3_5 colliderGameObject.active = false; #else colliderGameObject.SetActive(false); #endif break; case STATE.Dead: // the pasta is dead, // deactivate the gameobject #if UNITY_3_5 gameObject.active = false; #else gameObject.SetActive(false); #endif // disable other elements in case we jump straight to dead (like on a reset) #if UNITY_3_5 _liveAnimation.gameObject.SetActiveRecursively(false); #else _liveAnimation.gameObject.SetActive(false); #endif trailParticles.enableEmission = false; #if UNITY_3_5 colliderGameObject.active = false; #else colliderGameObject.SetActive(false); #endif break; } } } } /// <summary> /// Set up the pasta from the Pasta Manager /// </summary> /// <param name="manager">Reference to the game manager</param> public void Initialize(ROTD_GameManager manager) { // Set the state to initializing State = STATE.Initializing; // cache some references and perform calculations _gameManager = manager; _thisTransform = transform.transform; _trailTransform = trailParticles.transform; // instantiate the live animation GameObject go; go = (GameObject)Instantiate(liveAnimationPrefab, Vector3.zero, Quaternion.identity); go.transform.parent = _thisTransform; _liveAnimation = go.GetComponent<BoneAnimation>(); // register the live animation's delegates _liveAnimation.RegisterUserTriggerDelegate(LiveUserTrigger); _liveAnimation.RegisterColliderTriggerDelegate(LiveColliderTrigger); // start out dead State = STATE.Dead; } /// <summary> /// Set the pasta as active and initialize it's location /// </summary> public void ReSpawn() { // activate game objects #if UNITY_3_5 gameObject.active = true; _liveAnimation.gameObject.SetActiveRecursively(true); #else gameObject.SetActive(true); _liveAnimation.gameObject.SetActive(true); #endif // initialize variables _checkDirectionTimeLeft = 0; _healthLeft = health; // get the spawn position bool fromOven = false; _thisTransform.position = _gameManager.pastaManager.GetRandomRespawnPosition(out fromOven); if (fromOven) { _localEulerAngles = _liveAnimation.mLocalTransform.localEulerAngles; _localEulerAngles.y = 180.0f; _liveAnimation.mLocalTransform.localEulerAngles = _localEulerAngles; // Spawn if from oven State = STATE.Spawning; } else { // Wait to move if not from oven State = STATE.WaitingToMove; } } /// <summary> /// Called every frame /// </summary> public void FrameUpdate() { // if spawning, jump out if (_state == STATE.Spawning) return; // if dying if (_state == STATE.Dying) { if (!splatSound.isPlaying) { // set to dead if the splat sound is done playing State = STATE.Dead; } // jump out return; } // get the offset from the chef _offset = (_gameManager.chef.Position - _thisTransform.position); // get the rotation of the pasta based on its offset from the chef _localEulerAngles = _liveAnimation.mLocalTransform.localEulerAngles; _localEulerAngles.y = (_offset.x > 0 ? 180.0f : 0); _liveAnimation.mLocalTransform.localEulerAngles = _localEulerAngles; switch (_state) { case STATE.WaitingToMove: // pasta is waiting to move, so count down the timer _waitingToMoveTimeLeft -= Time.deltaTime; if (_waitingToMoveTimeLeft <= 0) { // countdown expired if (!InAttackRange(_offset)) { // out of attack range, so just move State = STATE.Moving; } } return; case STATE.Hitting: // move the pasta away from where it was hit by the player _position = _thisTransform.position; _position.x += (_hitXDirection * Time.deltaTime); // keep the pasta within the room bounds. This doesn't conform // to the room's apparant 3D shape, but it is close enough for // this minigame. _position.x = Mathf.Clamp(_position.x, _gameManager.room.roomXBoundsMinMax.x, _gameManager.room.roomXBoundsMinMax.y); _thisTransform.position = _position; break; case STATE.Attacking: // pasta is attacking // count down the check direction timer _checkDirectionTimeLeft -= Time.deltaTime; if (_checkDirectionTimeLeft <= 0) { // countdown expired if (!InAttackRange(_offset)) { // out of attack range, so just wait to move State = STATE.WaitingToMove; } // set the check direction countdown timer randomly between the set values _checkDirectionTimeLeft = UnityEngine.Random.Range(minMaxCheckDirectionTime.x, minMaxCheckDirectionTime.y); } break; case STATE.Moving: // pasta is moving // count down the check direction timer _checkDirectionTimeLeft -= Time.deltaTime; if (_checkDirectionTimeLeft <= 0) { // countdown expired // move in the direction of the offset from the chef _moveDirection = _offset; if (InAttackRange(_offset)) { // if in attack range, stop moving _moveDirection = Vector3.zero; } else { // out of attack range, so normalize the move direction _moveDirection.y = 0; _moveDirection.Normalize(); } // reset the check direction countdown timer _checkDirectionTimeLeft = UnityEngine.Random.Range(minMaxCheckDirectionTime.x, minMaxCheckDirectionTime.y); } // if the move direction is not empty if (_moveDirection != Vector3.zero) { // move in the direction stored _position = _thisTransform.position; _position += (_moveDirection * moveSpeed * Time.deltaTime); // make sure the pasta stays on the 45 degree slope by forcing the y value to the z value _position.y = _position.z; _thisTransform.position = _position; } break; } if (InAttackRange(_offset) && _state != STATE.Hitting) { // if in attack range and not getting hit, then attack State = STATE.Attacking; } else if (_state == STATE.Attacking) { // else if attacking, then wait to move State = STATE.WaitingToMove; } // set the trail Z position _position = _trailTransform.position; _position.z = trailZPosition; _trailTransform.position = _position; } /// <summary> /// Pasta gets hit /// </summary> /// <param name="collisionPoint">Location of the collision impact</param> /// <param name="damage">Amount of damage from the hit</param> public void Hit(Vector3 collisionPoint, float damage) { // if not already being hit if (_state != STATE.Hitting) { // play the hit sound hitSound.Play(); // Activate some sauce FX for gore _gameManager.fxManager.Activate(ROTD_FX.FX_TYPE.Sauce, _thisTransform.position, (int)(_thisTransform.position.x - _gameManager.chef.Position.x), ""); // damage the pasta _healthLeft -= damage; if (_healthLeft <= 0) { // the pasta ran out of health, so it is now dying State = STATE.Dying; // show a score and update the total score _gameManager.AddScore(_thisTransform.position); } else { // pasta still has some life left, so determine which direction it needs to fly and set its state to Hitting _hitXDirection = (collisionPoint.x > _thisTransform.position.x ? -hitMoveSpeed : hitMoveSpeed); State = STATE.Hitting; } } } /// <summary> /// Collider Trigger delegate for the live animation /// </summary> /// <param name="ctEvent">Event sent by the animation</param> public void LiveColliderTrigger(ColliderTriggerEvent ctEvent) { // if the collider event was an attack by the pasta if (ctEvent.tag == "Attack") { // only process enter event types (not stay or exit) if (ctEvent.triggerType == ColliderTriggerEvent.TRIGGER_TYPE.Enter) { // randomize the pitch of the attack sound for some variation attackSound.pitch = UnityEngine.Random.Range(minMaxAttackSoundPitch.x, minMaxAttackSoundPitch.y); // play the attack sound attackSound.Play(); // make the chef take damage _gameManager.chef.Hit(damage); } } } /// <summary> /// User trigger delegate for the live animation /// </summary> /// <param name="utEvent">Event sent by the animation</param> public void LiveUserTrigger(UserTriggerEvent utEvent) { if (utEvent.tag == "Hit Finished") { // if the event was a finished hit, then set the pasta // to a waiting to move state State = STATE.WaitingToMove; } else if (utEvent.tag == "Killable") { // if the event was a killable event, then make the collider active // (the collider starts out inactive when the pasta is spawning) #if UNITY_3_5 colliderGameObject.active = true; #else colliderGameObject.SetActive(true); #endif } else if (utEvent.tag == "Spawned") { // if the event is that the pasta has spawned, then // set its state to waiting to move State = STATE.WaitingToMove; } } /// <summary> /// Determines if an offset is within this pasta's attack range. /// Note that we could use vector magnitude, but because of the 2.5D nature of /// this minigame, the x and y offsets respond better when they are different values. /// </summary> /// <param name="offset">Offset from an object</param> /// <returns>True if in range</returns> private bool InAttackRange(Vector3 offset) { return (Mathf.Abs(offset.x) <= minAttackRange.x && Mathf.Abs(offset.y) <= minAttackRange.y); } }
using Microsoft.Data.Entity.Migrations; namespace AllReady.Migrations { public partial class TaskSignupAdditions : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.AddColumn<string>( name: "AdditionalInfo", table: "TaskSignup", nullable: true); migrationBuilder.AddColumn<string>( name: "PreferredEmail", table: "TaskSignup", nullable: true); migrationBuilder.AddColumn<string>( name: "PreferredPhoneNumber", table: "TaskSignup", nullable: true); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign", column: "ManagingOrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact", column: "OrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropColumn(name: "AdditionalInfo", table: "TaskSignup"); migrationBuilder.DropColumn(name: "PreferredEmail", table: "TaskSignup"); migrationBuilder.DropColumn(name: "PreferredPhoneNumber", table: "TaskSignup"); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign", column: "ManagingOrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact", column: "OrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.ComponentModel.EventBasedAsync.Tests { public class BackgroundWorkerTests { private const int TimeoutShort = 300; private const int TimeoutLong = 30000; [Fact] public void TestBackgroundWorkerBasic() { var orignal = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); const int expectedResult = 42; const int expectedReportCallsCount = 5; int actualReportCallsCount = 0; var worker = new BackgroundWorker() { WorkerReportsProgress = true }; var progressBarrier = new Barrier(2, barrier => ++actualReportCallsCount); var workerCompletedEvent = new ManualResetEventSlim(false); worker.DoWork += (sender, e) => { for (int i = 0; i < expectedReportCallsCount; i++) { worker.ReportProgress(i); progressBarrier.SignalAndWait(); } e.Result = expectedResult; }; worker.RunWorkerCompleted += (sender, e) => { try { Assert.Equal(expectedResult, (int)e.Result); Assert.False(worker.IsBusy); } finally { workerCompletedEvent.Set(); } }; worker.ProgressChanged += (sender, e) => { progressBarrier.SignalAndWait(); }; worker.RunWorkerAsync(); // wait for signal from WhenRunWorkerCompleted Assert.True(workerCompletedEvent.Wait(TimeoutLong)); Assert.False(worker.IsBusy); Assert.Equal(expectedReportCallsCount, actualReportCallsCount); } finally { SynchronizationContext.SetSynchronizationContext(orignal); } } [Fact] public void RunWorkerAsync_NoOnWorkHandler_SetsResultToNull() { var backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true }; bool isCompleted = false; backgroundWorker.RunWorkerCompleted += (sender, e) => { isCompleted = true; Assert.Null(e.Result); Assert.False(backgroundWorker.IsBusy); }; backgroundWorker.RunWorkerAsync(); var stopwatch = new Stopwatch(); stopwatch.Start(); while (!isCompleted) { if (stopwatch.Elapsed > TimeSpan.FromSeconds(10)) { throw new Exception("The background worker never completed."); } } } #region TestCancelAsync private ManualResetEventSlim manualResetEvent3; [Fact] public void TestCancelAsync() { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += DoWorkExpectCancel; bw.WorkerSupportsCancellation = true; manualResetEvent3 = new ManualResetEventSlim(false); bw.RunWorkerAsync("Message"); bw.CancelAsync(); bool ret = manualResetEvent3.Wait(TimeoutLong); Assert.True(ret); // there could be race condition between worker thread cancellation and completion which will set the CancellationPending to false // if it is completed already, we don't check cancellation if (bw.IsBusy) // not complete { if (!bw.CancellationPending) { for (int i = 0; i < 1000; i++) { Wait(TimeoutShort); if (bw.CancellationPending) { break; } } } // Check again if (bw.IsBusy) Assert.True(bw.CancellationPending, "Cancellation in Main thread"); } } private void DoWorkExpectCancel(object sender, DoWorkEventArgs e) { Assert.Equal("Message", e.Argument); var bw = sender as BackgroundWorker; if (bw.CancellationPending) { manualResetEvent3.Set(); return; } // we want to wait for cancellation - wait max (1000 * TimeoutShort) milliseconds for (int i = 0; i < 1000; i++) { Wait(TimeoutShort); if (bw.CancellationPending) { break; } } Assert.True(bw.CancellationPending, "Cancellation in Worker thread"); // signal no matter what, even if it's not cancelled by now manualResetEvent3.Set(); } #endregion [Fact] public void TestThrowExceptionInDoWork() { var original = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); const string expectedArgument = "Exception"; const string expectedExceptionMsg = "Exception from DoWork"; var bw = new BackgroundWorker(); var workerCompletedEvent = new ManualResetEventSlim(false); bw.DoWork += (sender, e) => { Assert.Same(bw, sender); Assert.Same(expectedArgument, e.Argument); throw new TestException(expectedExceptionMsg); }; bw.RunWorkerCompleted += (sender, e) => { try { TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => e.Result); Assert.True(ex.InnerException is TestException); Assert.Equal(expectedExceptionMsg, ex.InnerException.Message); } finally { workerCompletedEvent.Set(); } }; bw.RunWorkerAsync(expectedArgument); Assert.True(workerCompletedEvent.Wait(TimeoutLong), "Background work timeout"); } finally { SynchronizationContext.SetSynchronizationContext(original); } } [Fact] public void CtorTest() { var bw = new BackgroundWorker(); Assert.False(bw.IsBusy); Assert.False(bw.WorkerReportsProgress); Assert.False(bw.WorkerSupportsCancellation); Assert.False(bw.CancellationPending); } [Fact] public void RunWorkerAsyncTwice() { var bw = new BackgroundWorker(); var barrier = new Barrier(2); bw.DoWork += (sender, e) => { barrier.SignalAndWait(); barrier.SignalAndWait(); }; bw.RunWorkerAsync(); barrier.SignalAndWait(); try { Assert.True(bw.IsBusy); Assert.Throws<InvalidOperationException>(() => bw.RunWorkerAsync()); } finally { barrier.SignalAndWait(); } } [Fact] public void TestCancelInsideDoWork() { var original = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); var bw = new BackgroundWorker() { WorkerSupportsCancellation = true }; var barrier = new Barrier(2); bw.DoWork += (sender, e) => { barrier.SignalAndWait(); barrier.SignalAndWait(); if (bw.CancellationPending) { e.Cancel = true; } }; bw.RunWorkerCompleted += (sender, e) => { Assert.True(e.Cancelled); barrier.SignalAndWait(); }; bw.RunWorkerAsync(); barrier.SignalAndWait(); bw.CancelAsync(); barrier.SignalAndWait(); Assert.True(barrier.SignalAndWait(TimeoutLong), "Background work timeout"); } finally { SynchronizationContext.SetSynchronizationContext(original); } } [Fact] public void TestCancelAsyncWithoutCancellationSupport() { var bw = new BackgroundWorker() { WorkerSupportsCancellation = false }; Assert.Throws<InvalidOperationException>(() => bw.CancelAsync()); } [Fact] public void TestReportProgressSync() { var bw = new BackgroundWorker() { WorkerReportsProgress = true }; var expectedProgress = new int[] { 1, 2, 3, 4, 5 }; var actualProgress = new List<int>(); bw.ProgressChanged += (sender, e) => { actualProgress.Add(e.ProgressPercentage); }; foreach (int i in expectedProgress) { bw.ReportProgress(i); } Assert.Equal(expectedProgress, actualProgress); } [Fact] public void ReportProgress_NoProgressHandle_Nop() { var backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true }; foreach (int i in new int[] { 1, 2, 3, 4, 5 }) { backgroundWorker.ReportProgress(i); } } [Fact] public void TestReportProgressWithWorkerReportsProgressFalse() { var bw = new BackgroundWorker() { WorkerReportsProgress = false }; Assert.Throws<InvalidOperationException>(() => bw.ReportProgress(42)); } [Fact] public void DisposeTwiceShouldNotThrow() { var bw = new BackgroundWorker(); bw.Dispose(); bw.Dispose(); } [Fact] public void TestFinalization() { // BackgroundWorker has a finalizer that exists purely for backwards compatibility // with existing code that may override Dispose to clean up native resources. // https://github.com/dotnet/corefx/pull/752 ManualResetEventSlim mres = SetEventWhenFinalizedBackgroundWorker.CreateAndThrowAway(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.True(mres.Wait(10000)); } private sealed class SetEventWhenFinalizedBackgroundWorker : BackgroundWorker { private ManualResetEventSlim _setWhenFinalized; internal static ManualResetEventSlim CreateAndThrowAway() { var mres = new ManualResetEventSlim(); new SetEventWhenFinalizedBackgroundWorker() { _setWhenFinalized = mres }; return mres; } protected override void Dispose(bool disposing) { _setWhenFinalized.Set(); } } private static void Wait(int milliseconds) { Task.Delay(milliseconds).Wait(); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Microsoft.PythonTools.Parsing { /// <summary> /// Provides options for formatting code when calling Node.ToCodeString. /// /// By default a newly created CodeFormattingOptions will result in any /// source code being formatted to be round tripped identical to the original /// input code. Modifying any of the options from the defaults may result in /// the code being formatted according to the option. /// /// For boolean options setting to true will enable altering the code as described, /// and setting them to false will leave the code unmodified. /// /// For bool? options setting the option to true will modify the code one way, setting /// it to false will modify it another way, and setting it to null will leave the code /// unmodified. /// </summary> public sealed class CodeFormattingOptions { internal static CodeFormattingOptions Default = new CodeFormattingOptions(); // singleton with no options set, internal so no one mutates it private static Regex _commentRegex = new Regex("^[\t ]*#+[\t ]*"); private const string _sentenceTerminators = ".!?"; public string NewLineFormat { get; set; } #region Class Definition Options /// <summary> /// Space before the parenthesis in a class declaration. [CodeFormattingExample("class X (object): pass", "class X(object): pass")] [CodeFormattingCategory(CodeFormattingCategory.Classes)] [CodeFormattingDescription("SpaceBeforeClassDeclarationParenShort", "SpaceBeforeClassDeclarationParenLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceBeforeClassDeclarationParen { get; set; } /// <summary> /// Space after the opening paren and before the closing paren in a class definition. /// </summary> [CodeFormattingExample("class X( object ): pass", "class X(object): pass")] [CodeFormattingCategory(CodeFormattingCategory.Classes)] [CodeFormattingDescription("SpaceWithinClassDeclarationParensShort", "SpaceWithinClassDeclarationParensLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinClassDeclarationParens { get; set; } /// <summary> /// Space within empty base class list for a class definition. /// </summary> [CodeFormattingExample("class X( ): pass", "class X(): pass")] [CodeFormattingCategory(CodeFormattingCategory.Classes)] [CodeFormattingDescription("SpaceWithinEmptyBaseClassListShort", "SpaceWithinEmptyBaseClassListLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinEmptyBaseClassList { get; set; } #endregion #region Method Definition Options /* Method Definitions */ /// <summary> /// Space before the parenthesis in a function declaration. [CodeFormattingExample("def X (): pass", "def X(): pass")] [CodeFormattingCategory(CodeFormattingCategory.Functions)] [CodeFormattingDescription("SpaceBeforeFunctionDeclarationParenShort", "SpaceBeforeFunctionDeclarationParenLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceBeforeFunctionDeclarationParen { get; set; } /// <summary> /// Space after the opening paren and before the closing paren in a function definition. /// </summary> [CodeFormattingExample("def X( a, b ): pass", "def X(a, b): pass")] [CodeFormattingCategory(CodeFormattingCategory.Functions)] [CodeFormattingDescription("SpaceWithinFunctionDeclarationParensShort", "SpaceWithinFunctionDeclarationParensLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinFunctionDeclarationParens { get; set; } /// <summary> /// Space within empty parameter list for a function definition. /// </summary> [CodeFormattingExample("def X( ): pass", "def X(): pass")] [CodeFormattingCategory(CodeFormattingCategory.Functions)] [CodeFormattingDescription("SpaceWithinEmptyParameterListShort", "SpaceWithinEmptyParameterListLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinEmptyParameterList { get; set; } /// <summary> /// Spaces around the equals for a default value in a parameter list. /// </summary> [CodeFormattingExample("def X(a = 42): pass", "def X(a=42): pass")] [CodeFormattingCategory(CodeFormattingCategory.Functions)] [CodeFormattingDescription("SpaceAroundDefaultValueEqualsShort", "SpaceAroundDefaultValueEqualsLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceAroundDefaultValueEquals { get; set; } /// <summary> /// Spaces around the arrow annotation in a function definition. /// </summary> [CodeFormattingExample("def X() -> 42: pass", "def X()->42: pass")] [CodeFormattingCategory(CodeFormattingCategory.Functions)] [CodeFormattingDescription("SpaceAroundAnnotationArrowShort", "SpaceAroundAnnotationArrowLong")] [CodeFormattingDefaultValue(true)] public bool? SpaceAroundAnnotationArrow { get; set; } #endregion #region Function Call Options /// <summary> /// Space before the parenthesis in a call expression. /// </summary> [CodeFormattingExample("X ()", "X()")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpaceBeforeCallParenShort", "SpaceBeforeCallParenLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceBeforeCallParen { get; set; } /// <summary> /// Spaces within the parenthesis in a call expression with no arguments. /// </summary> [CodeFormattingExample("X( )", "X()")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpaceWithinEmptyCallArgumentListShort", "SpaceWithinEmptyCallArgumentListLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinEmptyCallArgumentList { get; set; } /// <summary> /// Space within the parenthesis in a call expression. /// </summary> [CodeFormattingExample("X( a, b )", "X(a, b)")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpaceWithinCallParensShort", "SpaceWithinCallParensLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinCallParens { get; set; } #endregion #region Other Spacing [CodeFormattingExample("( a )", "(a)")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpacesWithinParenthesisExpressionShort", "SpacesWithinParenthesisExpressionLong")] [CodeFormattingDefaultValue(false)] public bool? SpacesWithinParenthesisExpression { get; set; } [CodeFormattingExample("( )", "()")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpaceWithinEmptyTupleExpressionShort", "SpaceWithinEmptyTupleExpressionLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinEmptyTupleExpression { get; set; } [CodeFormattingExample("( a, b )", "(a, b)")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpacesWithinParenthesisedTupleExpressionShort", "SpacesWithinParenthesisedTupleExpressionLong")] [CodeFormattingDefaultValue(false)] public bool? SpacesWithinParenthesisedTupleExpression { get; set; } [CodeFormattingExample("[ ]", "[]")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpacesWithinEmptyListExpressionShort", "SpacesWithinEmptyListExpressionLong")] [CodeFormattingDefaultValue(false)] public bool? SpacesWithinEmptyListExpression { get; set; } [CodeFormattingExample("[ a, b ]", "[a, b]")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpacesWithinListExpressionShort", "SpacesWithinListExpressionLong")] [CodeFormattingDefaultValue(false)] public bool? SpacesWithinListExpression { get; set; } /* Index Expressions */ [CodeFormattingExample("x [i]", "x[i]")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpaceBeforeIndexBracketShort", "SpaceBeforeIndexBracketLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceBeforeIndexBracket { get; set; } [CodeFormattingExample("x[ i ]", "x[i]")] [CodeFormattingCategory(CodeFormattingCategory.Spacing)] [CodeFormattingDescription("SpaceWithinIndexBracketsShort", "SpaceWithinIndexBracketsLong")] [CodeFormattingDefaultValue(false)] public bool? SpaceWithinIndexBrackets { get; set; } #endregion #region Operators [CodeFormattingExample("a + b", "a+b")] [CodeFormattingCategory(CodeFormattingCategory.Operators)] [CodeFormattingDescription("SpacesAroundBinaryOperatorsShort", "SpacesAroundBinaryOperatorsLong")] [CodeFormattingDefaultValue(true)] public bool? SpacesAroundBinaryOperators { get; set; } [CodeFormattingExample("a = b", "a=b")] [CodeFormattingCategory(CodeFormattingCategory.Operators)] [CodeFormattingDescription("SpacesAroundAssignmentOperatorShort", "SpacesAroundAssignmentOperatorLong")] [CodeFormattingDefaultValue(true)] public bool? SpacesAroundAssignmentOperator { get; set; } #endregion #region Statements [CodeFormattingExample("import sys\r\nimport pickle", "import sys, pickle")] [CodeFormattingCategory(CodeFormattingCategory.Statements)] [CodeFormattingDescription("ReplaceMultipleImportsWithMultipleStatementsShort", "ReplaceMultipleImportsWithMultipleStatementsLong")] [CodeFormattingDefaultValue(true)] public bool ReplaceMultipleImportsWithMultipleStatements { get; set; } [CodeFormattingExample("x = 42", "x = 42;")] [CodeFormattingCategory(CodeFormattingCategory.Statements)] [CodeFormattingDescription("RemoveTrailingSemicolonsShort", "RemoveTrailingSemicolonsLong")] [CodeFormattingDefaultValue(true)] public bool RemoveTrailingSemicolons { get; set; } [CodeFormattingExample("x = 42\r\ny = 100", "x = 42; y = 100")] [CodeFormattingCategory(CodeFormattingCategory.Statements)] [CodeFormattingDescription("BreakMultipleStatementsPerLineShort", "BreakMultipleStatementsPerLineLong")] [CodeFormattingDefaultValue(true)] public bool BreakMultipleStatementsPerLine { get; set; } #endregion /* #region New Lines [CodeFormattingExample("# Specifies the number of lines which whould appear between top-level classes and functions")] [CodeFormattingCategory(CodeFormattingCategory.NewLines)] [CodeFormattingDescription("LinesBetweenLevelDeclarationsShort", "LinesBetweenLevelDeclarationsLong")] [CodeFormattingDefaultValue(2)] public int LinesBetweenLevelDeclarations { get; set; } [CodeFormattingExample("# Specifies the number of lines between methods in classes")] [CodeFormattingCategory(CodeFormattingCategory.NewLines)] [CodeFormattingDescription("LinesBetweenMethodsInClassShort", "LinesBetweenMethodsInClassLong")] [CodeFormattingDefaultValue(1)] public int LinesBetweenMethodsInClass { get; set; } [CodeFormattingExample("class C:\r\n def f(): pass\r\n\r\n def g(): pass", "class C:\r\n def f(): pass\r\n\r\n\r\n def g(): pass")] [CodeFormattingCategory(CodeFormattingCategory.NewLines)] [CodeFormattingDescription("RemoveExtraLinesBetweenMethodsShort", "RemoveExtraLinesBetweenMethodsLong")] [CodeFormattingDefaultValue(false)] public bool RemoveExtraLinesBetweenMethods { get; set; } #endregion*/ #region Wrapping [CodeFormattingExample("# Wrapped to 40 columns:\r\n# There should be one-- and preferably\r\n# only one --obvious way to do it.", "# Not wapped:\r\n# There should be one-- and preferably only one --obvious way to do it.")] [CodeFormattingCategory(CodeFormattingCategory.Wrapping)] [CodeFormattingDescription("WrapCommentsShort", "WrapCommentsLong")] [CodeFormattingDefaultValue(true)] public bool WrapComments { get; set; } [CodeFormattingExample("Sets the width for wrapping comments and doc strings.")] [CodeFormattingCategory(CodeFormattingCategory.Wrapping)] [CodeFormattingDescription("WrappingWidthShort", "WrappingWidthLong")] [CodeFormattingDefaultValue(80)] public int WrappingWidth { get; set; } #endregion /// <summary> /// Appends one of 3 strings depending upon a code formatting setting. The 3 settings are the on and off /// settings as well as the original formatting if the setting is not set. /// </summary> internal void Append(StringBuilder res, bool? setting, string ifOn, string ifOff, string originalFormatting) { if (!String.IsNullOrWhiteSpace(originalFormatting) || setting == null) { // there's a comment in the formatting, so we need to preserve it. ReflowComment(res, originalFormatting); } else { res.Append(setting.Value ? ifOn : ifOff); } } /// <summary> /// Given the whitespace from the proceeding line gets the whitespace that should come for following lines. /// /// This strips extra new lines and takes into account the code formatting new lines options. /// </summary> internal string GetNextLineProceedingText(string proceeding) { int newLine; var additionalProceeding = proceeding; if ((newLine = additionalProceeding.LastIndexOfAny(new[] { '\r', '\n' })) == -1) { additionalProceeding = (NewLineFormat ?? Environment.NewLine) + proceeding; } else { // we just want to capture the indentation, not multiple newlines. additionalProceeding = (NewLineFormat ?? Environment.NewLine) + proceeding.Substring(newLine + 1); } return additionalProceeding; } internal void ReflowComment(StringBuilder res, string text) { if (!WrapComments || String.IsNullOrWhiteSpace(text) || text.IndexOf('#') == -1) { res.Append(text); return; } // figure out how many characters we have on the line not related to the comment, // we'll try and align with this. For example: // (1, # This is a comment which will be wrapped // 2, ... // Should wrap to: // (1, # This is a comment // # which will be wrapped // 2, // int charsOnCurrentLine = GetCharsOnLastLine(res); var lines = text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); int lineCount = lines.Length; if (text.EndsWith("\r") || text.EndsWith("\n")) { // split will give us an extra entry, but there's not really an extra line lineCount = lines.Length - 1; } int reflowStartingLine = 0, curLine = 0; do { string commentPrefix = GetCommentPrefix(lines[curLine]); if (commentPrefix == null) { // non-commented line (empty?), just append it and continue // to the next comment prefix if we have one res.Append(lines[curLine] + (curLine == lineCount - 1 ? "" : (NewLineFormat ?? Environment.NewLine))); charsOnCurrentLine = GetCharsOnLastLine(res); reflowStartingLine = curLine + 1; } else if (curLine == lineCount - 1 || GetCommentPrefix(lines[curLine + 1]) != commentPrefix) { // last line, or next line mismatches with our comment prefix. So reflow the text now res.Append( ReflowText( commentPrefix, new string(' ', charsOnCurrentLine) + commentPrefix, // TODO: Tabs instead of spaces NewLineFormat ?? Environment.NewLine, WrappingWidth, lines.Skip(reflowStartingLine).Take(curLine - reflowStartingLine + 1).ToArray() ) ); reflowStartingLine = curLine + 1; } } while (++curLine < lineCount); } private static int GetCharsOnLastLine(StringBuilder res) { for (int i = res.Length - 1; i >= 0; i--) { if (res[i] == '\n' || res[i] == '\r') { return res.Length - i - 1; } } return res.Length; } internal static string GetCommentPrefix(string text) { var match = _commentRegex.Match(text); if (match.Success) { return text.Substring(0, match.Length); } return null; } internal static string ReflowText(string prefix, string additionalLinePrefix, string newLine, int maxLength, string[] lines) { int curLine = 0, curOffset = prefix.Length, linesWritten = 0; int columnCutoff = maxLength - prefix.Length; int defaultColumnCutoff = columnCutoff; StringBuilder newText = new StringBuilder(); while (curLine < lines.Length) { string curLineText = lines[curLine]; int lastSpace = curLineText.Length; // skip leading white space while (curOffset < curLineText.Length && Char.IsWhiteSpace(curLineText[curOffset])) { curOffset++; } // find next word for (int i = curOffset; i < curLineText.Length; i++) { if (Char.IsWhiteSpace(curLineText[i])) { lastSpace = i; break; } } bool startNewLine = lastSpace - curOffset >= columnCutoff && // word won't fit in remaining space columnCutoff != defaultColumnCutoff; // we're not already at the start of a new line if (!startNewLine) { // we found a like break in the region and it's a reasonable size or // we have a really long word that we need to append unbroken if (columnCutoff == defaultColumnCutoff) { // first time we're appending to this line newText.Append(linesWritten == 0 ? prefix : additionalLinePrefix); } newText.Append(curLineText, curOffset, lastSpace - curOffset); // append appropriate spacing if (_sentenceTerminators.IndexOf(curLineText[lastSpace - 1]) != -1 || // we end in punctuation ((lastSpace - curOffset) > 1 && // we close a paren that ends in punctuation curLineText[lastSpace - curOffset] == ')' && _sentenceTerminators.IndexOf(curLineText[lastSpace - 2]) != -1)) { newText.Append(" "); columnCutoff -= lastSpace - curOffset + 2; } else { newText.Append(' '); columnCutoff -= lastSpace - curOffset + 1; } curOffset = lastSpace + 1; // if we reached the end of the line preserve the existing line break. startNewLine = curOffset >= lines[curLine].Length; } if (startNewLine) { // remove any trailing white space while (newText.Length > 0 && newText[newText.Length - 1] == ' ') { newText.Length = newText.Length - 1; } linesWritten++; newText.Append(newLine); columnCutoff = defaultColumnCutoff; } if (curOffset >= lines[curLine].Length) { // we're now reading from the next line curLine++; curOffset = prefix.Length; } } return newText.ToString(); } } }
namespace RegularExpressionScratchpad { using System; using System.Drawing; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using System.Xml.Serialization; using RegularExpressionScratchpad.Properties; /// <summary> /// Main Form /// </summary> public partial class MainForm : Form { private RegexBuffer buffer; private int regexInsertionPoint = -1; private DirectoryInfo dir; private Regex parseRegEx; private RegularExpressionLibrary mylibrary; /// <summary> /// Initializes a new instance of the <see cref="MainForm"/> class. /// </summary> public MainForm() { this.InitializeComponent(); } /// <summary> /// Interprets the reg ex. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Intended")] private void InterpretRegEx() { this.buffer = new RegexBuffer(this.textBoxRegex.Text) { RegexOptions = this.CreateRegexOptions() }; try { RegexExpression exp = new RegexExpression(this.buffer); this.textBoxInterpretation.Text = exp.ToString(0); this.textBoxInterpretation.ForeColor = Color.Black; } catch (Exception ex) { this.textBoxInterpretation.Text = "We have a situation...\r\n\r\n (" + ex.Message + ")"; this.textBoxRegex.Focus(); this.textBoxInterpretation.ForeColor = Color.Gray; } } /// <summary> /// Creates the regex options. /// </summary> /// <returns>RegexOptions</returns> private RegexOptions CreateRegexOptions() { RegexOptions regOp = new RegexOptions(); if (this.checkedListBoxOptions.CheckedItems.Contains("Ignore whitespace")) { regOp |= RegexOptions.IgnorePatternWhitespace; } if (this.checkedListBoxOptions.CheckedItems.Contains("Ignore case")) { regOp |= RegexOptions.IgnoreCase; } if (this.checkedListBoxOptions.CheckedItems.Contains("Explicit capture")) { regOp |= RegexOptions.ExplicitCapture; } if (this.checkedListBoxOptions.CheckedItems.Contains("Singleline")) { regOp |= RegexOptions.Singleline; } if (this.checkedListBoxOptions.CheckedItems.Contains("Multiline")) { regOp |= RegexOptions.Multiline; } if (this.checkedListBoxOptions.CheckedItems.Contains("Right to left")) { regOp |= RegexOptions.RightToLeft; } return regOp; } /// <summary> /// Replaces the text. /// </summary> private void ReplaceText() { try { Regex regex = this.CreateRegex(); string[] strings; // if checked, pass all lines as a single block if (this.checkBoxTreatAsSingleString.Checked) { strings = new string[1]; strings[0] = this.textBoxInput.Text; } else { strings = Regex.Split(this.textBoxInput.Text, @"\r\n"); // strings = Strings.Text.Split('\n\r'); } StringBuilder outString = new StringBuilder(); string replace = this.textBoxReplacement.Text; foreach (string s in strings) { outString.Append(regex.Replace(s, replace)); } this.textBoxInput.SelectionColor = Color.Black; this.textBoxInput.SelectionFont = new Font("Arial", 10, FontStyle.Regular); this.textBoxInput.Text = outString.ToString(); } catch (Exception ex) { this.ShowException(ex); } } /// <summary> /// Shows the exception. /// </summary> /// <param name="ex">The ex.</param> private void ShowException(Exception ex) { StringBuilder error = new StringBuilder(); error.Append("An error has occured:\r\n"); error.Append(ex.Message); this.textBoxInput.Text = error.ToString(); this.textBoxInput.Find("An error has occured:", 0, RichTextBoxFinds.MatchCase); this.textBoxInput.SelectionFont = new Font("Arial", 10, FontStyle.Bold); this.textBoxInput.SelectionColor = Color.Red; } /// <summary> /// Creates the regex. /// </summary> /// <returns>regex</returns> private Regex CreateRegex() { RegexOptions regOp = this.CreateRegexOptions(); return new Regex(this.textBoxRegex.Text, regOp); } /// <summary> /// Handles the TextChanged event of the textBoxRegex control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void TextBoxRegex_TextChanged(object sender, EventArgs e) { this.InterpretRegEx(); } /// <summary> /// Handles the DragEnter event of the textBoxInput control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.DragEventArgs"/> instance containing the event data.</param> private void TextBoxInput_DragEnter(object sender, DragEventArgs e) { // If the data is a file or a bitmap, display the copy cursor. e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop) ? DragDropEffects.Copy : DragDropEffects.None; } /// <summary> /// Handles the dragdrop event of the textBoxInput control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.DragEventArgs"/> instance containing the event data.</param> private void TextBoxInput_dragdrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); try { using (StreamReader sr = new StreamReader(files[0])) { this.textBoxInput.Text = sr.ReadToEnd(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } /// <summary> /// Handles the Click event of the ToolStripButtonReplace control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void ToolStripButtonReplace_Click(object sender, EventArgs e) { this.ReplaceText(); } /// <summary> /// Inserts the text. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void InsertText(object sender, EventArgs e) { ToolStripMenuItem menuItem = (ToolStripMenuItem)sender; Regex regexBreak = new Regex(".+: (?<Placeholder>.+)"); Match match = regexBreak.Match(menuItem.Text); if (match.Success) { string insert = match.Groups["Placeholder"].ToString(); this.regexInsertionPoint = this.textBoxRegex.SelectionStart; string start = this.textBoxRegex.Text.Substring(0, this.regexInsertionPoint); string end = this.textBoxRegex.Text.Substring(this.regexInsertionPoint); this.textBoxRegex.Text = start + insert + end; Regex regexSelect = new Regex("(?<Select><[^<]+?>)"); match = regexSelect.Match(insert); if (match.Success) { Group g = match.Groups["Select"]; this.textBoxRegex.SelectionStart = this.regexInsertionPoint + g.Index; this.textBoxRegex.SelectionLength = g.Length; } else { this.textBoxRegex.SelectionStart = this.regexInsertionPoint; } this.textBoxRegex.Focus(); this.textBoxRegex.Select(this.textBoxRegex.Text.Length, 0); } } /////// <summary> /////// Handles the KeyDown event of the TextBoxRegex control. /////// </summary> /////// <param name="sender">The source of the event.</param> /////// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param> ////private void TextBoxRegex_KeyDown(object sender, KeyEventArgs e) ////{ //// if (e.KeyCode.ToString() == "Return") //// { //// this.ReplaceText(); //// this.InterpretRegEx(); //// e.SuppressKeyPress = true; //// } ////} /// <summary> /// Handles the Load event of the MainForm control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void MainForm_Load(object sender, EventArgs e) { this.Width = Convert.ToInt32(Settings.Default.WindowWidth); this.Height = Convert.ToInt32(Settings.Default.WindowHeight); this.LoadRegularExpressionLibrary(); this.textBoxRegex.Focus(); } /// <summary> /// Loads the regular expression library. /// </summary> private void LoadRegularExpressionLibrary() { if (File.Exists(Application.StartupPath + @"\RegExLibrary.xml") == false) { this.treeView1.Enabled = false; this.toolStripButtonLibrary.Enabled = false; this.labelLibrary.Text = "Task Library not Available"; return; } try { // Construct an instance of the XmlSerializer with the type // of object that is being deserialized. XmlSerializer serializer = new XmlSerializer(typeof(RegularExpressionLibrary)); // To read the file, create a FileStream. using (FileStream fileStream = new FileStream(Application.StartupPath + @"\RegExLibrary.xml", FileMode.Open)) { // Call the Deserialize method and cast to the object type. this.mylibrary = (RegularExpressionLibrary)serializer.Deserialize(fileStream); } foreach (Library lib in this.mylibrary.Library) { TreeNode libNode = new TreeNode(lib.libraryname); foreach (task t in lib.task) { TreeNode taskNode = new TreeNode(t.name); libNode.Nodes.Add(taskNode); } this.treeView1.Nodes.Add(libNode); } this.treeView1.Enabled = true; this.toolStripButtonLibrary.Enabled = true; this.labelLibrary.Text = "Task Library"; } catch (Exception ex) { MessageBox.Show("There was en error loading the Regular Expression Library: " + Environment.NewLine + ex.Message, "Library Error", MessageBoxButtons.OK, MessageBoxIcon.Error); this.treeView1.Enabled = false; } } /// <summary> /// Handles the Click event of the toolStripButton2 control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void ToolStripButton2_Click(object sender, EventArgs e) { int characterCount = this.textBoxInput.Text.Length; int difference = 999; while (difference > 0) { this.DoWork(); int currentcount = this.textBoxInput.Text.Length; difference = characterCount - currentcount; characterCount = currentcount; } } /// <summary> /// Does the work. /// </summary> private void DoWork() { int taskCount = 0; foreach (TreeNode libraryNode in this.treeView1.Nodes) { foreach (TreeNode taskNode in libraryNode.Nodes) { if (taskNode.Checked) { taskCount++; } } } if (taskCount > 0) { foreach (TreeNode libraryNode in this.treeView1.Nodes) { foreach (TreeNode taskNode in libraryNode.Nodes) { if (taskNode.Checked) { this.ProcessLibraryTask(libraryNode.Text, taskNode.Text); this.Refresh(); } } } } } /// <summary> /// Processes the library task. /// </summary> /// <param name="library">The library.</param> /// <param name="task">The task.</param> private void ProcessLibraryTask(string library, string task) { foreach (Library t1 in this.mylibrary.Library) { if (t1.libraryname == library) { foreach (task t in t1.task) { if (t.name == task) { foreach (action a in t.action) { Regex regex = new Regex(a.pattern); if (a.supportsRecursion) { while (regex.Match(this.textBoxInput.Text).Success) { this.textBoxInput.Text = regex.Replace(this.textBoxInput.Text, a.replacement); } } else { this.textBoxInput.Text = regex.Replace(this.textBoxInput.Text, a.replacement); } } } } } } } /// <summary> /// Handles the Click event of the toolStripButton3 control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void ToolStripButton3_Click(object sender, EventArgs e) { // RegExLibrary library = new RegExLibrary(); LibraryXml library = new LibraryXml(); library.Show(); } /// <summary> /// Handles the AfterCheck event of the treeView1 control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.TreeViewEventArgs"/> instance containing the event data.</param> private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) { foreach (TreeNode childNode in e.Node.Nodes) { childNode.Checked = e.Node.Checked; } } /// <summary> /// Handles the Click event of the toolStripDropDownButton1 control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void toolStripDropDownButton1_Click(object sender, EventArgs e) { using (AboutForm aboutForm = new AboutForm()) { aboutForm.ShowDialog(); } } /// <summary> /// Handles the Click event of the toolStripButtonReplaceInFiles control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void toolStripButtonReplaceInFiles_Click(object sender, EventArgs e) { try { this.folderBrowserDialog1.Description = "Select a path to Run the replacement on"; DialogResult result = this.folderBrowserDialog1.ShowDialog(); if (result == DialogResult.OK) { this.dir = new DirectoryInfo(this.folderBrowserDialog1.SelectedPath); this.ReplaceInFiles(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Unexpected Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// <summary> /// Fixes this instance. /// </summary> private void ReplaceInFiles() { // Load the regex to use this.parseRegEx = this.CreateRegex(); // Call the GetFileSystemInfos method. FileSystemInfo[] infos = this.dir.GetFileSystemInfos("*"); // Iterate through each item. foreach (FileSystemInfo i in infos) { // Check to see if this is a FileInfo object. if (i is FileInfo) { this.ParseAndReplaceFile(i); } } MessageBox.Show("Replacement Complete", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information); } /// <summary> /// Parses the and replace file. /// </summary> /// <param name="parseFile">The parse file.</param> private void ParseAndReplaceFile(FileSystemInfo parseFile) { // Open the file and attempt to read the encoding from the BOM. string entireFile; using (StreamReader streamReader = new StreamReader(parseFile.FullName, true)) { entireFile = streamReader.ReadToEnd(); } // Parse the entire file. string newFile = this.parseRegEx.Replace(entireFile, this.textBoxReplacement.Text); // First make sure the file is writable. FileAttributes fileAttributes = File.GetAttributes(parseFile.FullName); // If readonly attribute is set, reset it. if ((fileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { File.SetAttributes(parseFile.FullName, fileAttributes ^ FileAttributes.ReadOnly); } // Write out the new file. using (StreamWriter streamWriter = new StreamWriter(parseFile.FullName.Replace("dbo.p_Service", string.Empty).Replace(".StoredProcedure", string.Empty), false)) { streamWriter.Write(newFile); } } /// <summary> /// Handles the ResizeEnd event of the MainForm control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void MainForm_ResizeEnd(object sender, EventArgs e) { Settings.Default.WindowHeight = this.Height.ToString(); Settings.Default.WindowWidth = this.Width.ToString(); Settings.Default.Save(); } /// <summary> /// Handles the Click event of the toolStripButton1 control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void toolStripButton1_Click(object sender, EventArgs e) { MatcherForm matcher = new MatcherForm(); matcher.Show(); } /// <summary> /// Handles the Click event of the toolStripMatch control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void toolStripMatch_Click(object sender, EventArgs e) { this.Match(); } /// <summary> /// Matches this instance. /// </summary> private void Match() { try { this.textBoxInput.SelectAll(); this.textBoxInput.SelectionFont = new Font(this.textBoxInput.Font.Name, this.textBoxInput.Font.Size, FontStyle.Regular); this.textBoxInput.SelectionColor = Color.Black; this.textBoxInput.SelectionBackColor = Color.White; this.textBoxInput.Select(0, 0); Regex regex = this.CreateRegex(); Match m = regex.Match(this.textBoxInput.Text); while (m.Success) { Group g = m.Groups[0]; CaptureCollection cc = g.Captures; for (int j = 0; j < cc.Count; j++) { Capture c = cc[j]; this.textBoxInput.Select(c.Index, c.Length); this.textBoxInput.SelectionColor = Color.Red; this.textBoxInput.SelectionBackColor = Color.Yellow; } m = m.NextMatch(); } this.textBoxInput.ScrollToCaret(); } catch (Exception ex) { this.ShowException(ex); } } /// <summary> /// Handles the KeyDown event of the textBoxRegex control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param> private void textBoxRegex_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode.ToString() == "Return") { this.Match(); e.SuppressKeyPress = true; } } } }
using System; using GoogleApi.Entities.Search.Common.Enums; using GoogleApi.Entities.Search.Common.Enums.Extensions; using GoogleApi.Entities.Search.Web.Request; using NUnit.Framework; namespace GoogleApi.UnitTests.Search.Web { [TestFixture] public class WebSearchRequestTests { [Test] public void ConstructorDefaultTest() { var request = new WebSearchRequest(); Assert.IsTrue(request.PrettyPrint); Assert.AreEqual(request.Alt, AltType.Json); } [Test] public void GetQueryStringParametersTest() { var request = new WebSearchRequest { Key = "abc", SearchEngineId = "abc", Query = "abc" }; Assert.DoesNotThrow(() => request.GetQueryStringParameters()); } [Test] public void GetQueryStringParametersWhenKeyIsNullTest() { var request = new WebSearchRequest { Key = null }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "Key is required"); } [Test] public void GetQueryStringParametersWhenKeyIsStringEmptyTest() { var request = new WebSearchRequest { Key = string.Empty }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "Key is required"); } [Test] public void GetQueryStringParametersWhenQueryIsNullTest() { var request = new WebSearchRequest { Key = "abc", Query = null }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "Query is required"); } [Test] public void GetQueryStringParametersWhenQueryIsStringEmptyTest() { var request = new WebSearchRequest { Key = "abc", Query = string.Empty }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "Query is required"); } [Test] public void GetQueryStringParametersWhenSearchEngineIdIsNullTest() { var request = new WebSearchRequest { Key = "abc", Query = "google", SearchEngineId = null }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "SearchEngineId is required"); } [Test] public void GetQueryStringParametersWhenSearchEngineIdIsStringEmptyTest() { var request = new WebSearchRequest { Key = "abc", Query = "google", SearchEngineId = string.Empty }; var exception = Assert.Throws<ArgumentException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "SearchEngineId is required"); } [Test] public void GetQueryStringParametersWhenOptionsNumberIsLessThanOneTest() { var request = new WebSearchRequest { Key = "abc", Query = "google", SearchEngineId = "abc", Options = { Number = 0 } }; var exception = Assert.Throws<InvalidOperationException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "Number must be between 1 and 10"); } [Test] public void GetQueryStringParametersWhenOptionsNumberIsGreaterThanTenTest() { var request = new WebSearchRequest { Key = "abc", Query = "google", SearchEngineId = "abc", Options = { Number = 11 } }; var exception = Assert.Throws<InvalidOperationException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, "Number must be between 1 and 10"); } [Test] public void GetQueryStringParametersWhenSafetyLevelInterfaceLanguageIsNotSupportedTest() { var request = new WebSearchRequest { Key = "abc", Query = "google", SearchEngineId = "abc", Options = { SafetyLevel = SafetyLevel.Medium, InterfaceLanguage = Language.Afrikaans } }; var exception = Assert.Throws<InvalidOperationException>(() => { var parameters = request.GetQueryStringParameters(); Assert.IsNull(parameters); }); Assert.AreEqual(exception.Message, $"SafetyLevel is not allowed for specified InterfaceLanguage: {request.Options.InterfaceLanguage}"); } [Test] public void GetUriTest() { var request = new WebSearchRequest { Key = "abc", SearchEngineId = "abc", Query = "abc" }; var uri = request.GetUri(); Assert.IsNotNull(uri); Assert.AreEqual($"/customsearch/v1?key={request.Key}&q={request.Query}&alt={request.Alt.ToString().ToLower()}&prettyPrint={request.PrettyPrint.ToString().ToLower()}&cx={request.SearchEngineId}&c2coff=1&fileType={string.Join(",", request.Options.FileTypes)}&filter=0&hl={request.Options.InterfaceLanguage.ToHl()}&num={request.Options.Number}&rights={string.Join(",", request.Options.Rights)}&safe={request.Options.SafetyLevel.ToString().ToLower()}&start={request.Options.StartIndex.ToString()}", uri.PathAndQuery); } [Test] public void GetUriWhenCallbackTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenFieldsTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenCountryRestrictionTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenDateRestrictionTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenExactTermsTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenExcludeTermsTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenGoogleHostTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenHighRangeTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenAndTermsTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenLinkSiteTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenLowRangeTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenNumberTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenOrTermsTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenRelatedSiteTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenSearchTypeTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenSiteSearchTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenSiteSearchFilterTest() { Assert.Inconclusive(); } [Test] public void GetUriWhenSortExpressionTest() { Assert.Inconclusive(); } } }